source: TI01-discovery/branches/ingestAutomation-upgrade/OAIBatch/DeleteRecord.py @ 5687

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI01-discovery/branches/ingestAutomation-upgrade/OAIBatch/DeleteRecord.py@6130
Revision 5687, 5.8 KB checked in by sdonegan, 10 years ago (diff)

Updated to handle lower case dif format spec from info editor..

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2'''
3Test class to test deletions from discovery postgres database
4'''
5import sys, os, getopt, logging
6from ndg.common.src.clients.reldb.postgres.postgresclient import PostgresClient as pgc
7from PostgresDAO import PostgresDAO
8from PostgresRecord import PostgresRecord
9from RecordToDelete import RecordToDelete
10from Utilities import RecordToDelete
11
12class DeleteRecord:
13       
14       
15    def _getPostgresDBConnection(self):
16        '''
17        Get the default postgres DB connection - by reading in data from the db config file
18        '''       
19        logging.debug("Setting up connection to postgres DB")
20        self.pgc = pgc(configFile = 'ingest.config')
21        logging.info("Postgres DB connection now set up")
22       
23       
24    def createRecordObject(self,record,dao,recordFilename):
25       
26        '''
27        Simple method to simplify addition of filename and localid
28        '''
29       
30        #work out whether searching using supplied filename or discoveryID
31        if recordFilename is None:
32            dao.getRecordID()
33        else: 
34            dao.getRecordID_using_OriginalDocumentFilename()
35            dao.getDiscoveryID_using_OriginalDocumentFilename()
36       
37       
38    def usage(self):
39        '''
40        Display input params for the script
41        '''
42        print "Usage: python testDeletions.py [OPTION] <metadata file>"
43        print " - where:\n   <metadata file> is the file to delete from the postgres database in ingest.config; and options are:"
44        print " -v - verbose mode for output logging"
45        print " -d - debug mode for output logging"
46        sys.exit(2)
47       
48   
49    def __init__(self,fileToDelete=None):
50        '''
51        Main entry point for script
52        '''
53        self.lineSeparator = "-----------------------------"
54       
55        print self.lineSeparator
56        print "RUNNING: DeleteRecord.py"
57       
58        # check for verbose option
59        try:
60            opts, args = getopt.getopt(sys.argv[1:], "vd")
61        except getopt.GetoptError, err:
62            # print help information and exit:
63            print str(err) # will print something like "option -a not recognized"
64           
65        loggingLevel = logging.WARNING
66        for o, a in opts:
67            if o == "-v":
68                print " - Verbose mode ON"
69                loggingLevel = logging.INFO
70            elif o == "-d":
71                print " - Debug mode ON"
72                loggingLevel = logging.DEBUG
73       
74        print self.lineSeparator
75       
76        logging.basicConfig(level=loggingLevel,format='%(asctime)s %(filename)s:%(lineno)d %(levelname)s %(message)s')
77       
78        if fileToDelete is None:
79            self.usage()
80       
81        #test whether supplied file is an xml file (in straight non -OAI altered name or with OAI stuff in OR just a discovery ID)       
82        if fileToDelete.endswith(".xml"):
83           
84            #does filename have any altered OAI nomenclature?
85            if fileToDelete.find("%3A") != -1:
86                recordFilename =  fileToDelete[fileToDelete.rindex("%3A")+3:len(fileToDelete)]
87                logging.info("Have extracted localised original file name from OAI altered one: " + recordFilename)
88            else:
89                recordFilename = fileToDelete
90                logging.info("Local file name to extract: " + recordFilename)
91           
92            discoveryID = None
93           
94            logging.info("record filename === "+ recordFilename)
95           
96        else:
97            #consider as DiscoveryID
98            recordFilename = None
99            discoveryID = fileToDelete
100            logging.info("Discovery ID of file to extract: " + discoveryID)
101       
102       
103        #self._dbConnection = None
104        self._getPostgresDBConnection()
105                   
106        #are we dealing with a FILE to delete or a discoveryID
107        if recordFilename is not None:
108           
109            #find record based on filename
110            #create basic record object - only need the id
111            record = RecordToDelete(recordFilename,None)
112            logging.info("Getting discoveryId from database for  %s" %recordFilename)     
113            dao = PostgresDAO(record, self.pgc)             
114            self.createRecordObject(record,dao,recordFilename)
115           
116        else:
117            #find record based on ID
118            record = RecordToDelete(None,discoveryID)
119            logging.info("Getting discoveryId from database for  %s" %discoveryID)     
120            dao = PostgresDAO(record, self.pgc)             
121            self.createRecordObject(record,dao,recordFilename)
122       
123        #check to see whether a record with this discoveryID actually exists in there
124        if record.db_id is not None:
125       
126            #delete original record
127            try:           
128                dao.deleteOriginalRecord()
129                dao._deleteSpatioTemporalData()
130               
131                #check item deleted (note need to reinitialise the record object!)
132                dao = PostgresDAO(record, self.pgc)
133                record = RecordToDelete(recordFilename,None)
134                self.createRecordObject(record,dao,recordFilename)
135               
136                if record.db_id is None:
137                    print "HAVE SUCCESSFULLY DELETED DOCUMENT FROM DATABASE"
138               
139            except Exception, detail:
140                logging.error("Could not delete record! %s" %detail)
141           
142        else:
143            logging.warn("Could not detect record in database for: " + fileToDelete)
144           
145       
146       
147
148if __name__=="__main__":
149   
150    opts, args = getopt.getopt(sys.argv[1:], '-vd')
151   
152    if len(args) < 1:
153        DeleteRecord()
154   
155    DeleteRecord(args[0])
156   
157   
Note: See TracBrowser for help on using the repository browser.