This repository has been archived by the owner on Sep 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenome_tree_backend.py
1632 lines (1278 loc) · 58.9 KB
/
genome_tree_backend.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#####################################################
# genome_tree_backend.py
#
# PostgreSQL interface for PhylogeneticM
#
# Documentation written in NaturalDocs format
#
#####################################################
import sys
import os
import re
import subprocess
import tempfile
import time
import random
import string
import xml.etree.ElementTree as et
import xml_funcs
from xml.sax.saxutils import escape
import shutil
# Import extension modules
import psycopg2 as pg
import bcrypt
from simplehmmer.simplehmmer import HMMERRunner, HMMERParser
from simplehmmer.hmmmodelparser import HmmModelParser
from metachecka2000.dataConstructor import HMMERError, Mc2kHmmerDataConstructor as DataConstructor
from metachecka2000.resultsParser import HMMAligner
from metachecka2000.resultsParser import Mc2kHmmerResultsParser as QaParser
# Import Genome Tree Database modules
import profiles
# Section: PhylogeneticM API
# Class: User
# A class that represents a user of the database
class User(object):
# Constuctor: User
# Initialises the object
def __init__(self, userId, userName, typeId):
self.userId = userId
self.userName = userName
self.typeId = typeId
# Function: getUserName
# Returns the username of the user
#
# Returns:
# The username of the User as a string
def getUserName(self):
return self.userName
# Function: getUserId
# Returns the id of the user (as stored in PostgreSQL database)
def getUserId(self):
return self.userId
# Function: getTypeId
# Returns the type id of this user
def getTypeId(self):
return self.typeId
# Class: GenomeDatabase
# A class that represents a user of the database
class GenomeDatabase(object):
def __init__(self):
self.conn = None
self.currentUser = None
self.lastErrorMessage = None
self.debugMode = False
#
# Group: General Functions
#
# Function: ReportError
# Sets the last error message of the database.
#
# Parameters:
# msg - The message to set.
#
# Returns:
# No return value.
def ReportError(self, msg):
self.lastErrorMessage = str(msg) + "\n"
# Function: SetDebugMode
# Sets the debug mode of the database (at the moment its either on (non-zero) or off (zero))
#
# Parameters:
# debug_mode - The debug mode to set.
#
# Returns:
# No return value.
def SetDebugMode(self, debug_mode):
self.debugMode = debug_mode
# Function: AddLargeObject
# Adds a PostgreSQL large object to the database.
#
# Parameters:
# filename - The path to the file to add.
#
# Returns:
# The object id (oid) of the added object.
def AddLargeObject(self, filename):
lobject = self.conn.lobject(0, 'w', 0, filename)
lobject.close()
self.conn.commit()
return lobject.oid
# Function: DeleteLargeObject
# Deletes a PostgreSQL large object from the database.
#
# Parameters:
# oid - The object id of the large object to delete.
#
# Returns:
# No return value.
def DeleteLargeObject(self, oid):
lobject = self.conn.lobject(oid, 'w')
lobject.unlink()
self.conn.commit()
#
# Group: Database Connection Functions
#
# Function: MakePostgresConnection
# Opens a connection to the PostgreSQL database
#
# Parameters:
# port - The port on which the postgres server is listening (default: None (which will default to the standard PostgreSQL server port))
#
# Returns:
# No return value.
def MakePostgresConnection(self, port=None):
conn_string = "dbname=genome_tree user=uqaskars host=/tmp/"
if port is not None:
conn_string += " port=" + str(port)
self.conn = pg.connect(conn_string)
# Function: ClosePostgresConnection
# Closes an open connection to the PostgreSQL database.
#
# Returns:
# No return value.
def ClosePostgresConnection(self):
self.conn.close()
self.conn = None
# Function: IsPostgresConnectionActive
# Check if the connection to the PostgreSQL database is active.
#
# Returns:
# True if connection is active, False otherwise
def IsPostgresConnectionActive(self):
if self.conn is not None:
cur = self.conn.cursor()
try:
cur.execute("SELECT * from genomes")
except:
return False
cur.close()
return True
else:
return False
#
# Group: Password/User Functions
#
# Function: GenerateRandomPassword
# Generates a random password (plain-text)
#
# Parameters:
# length - The length of the generated password (default: 8)
#
# Returns:
# True if connection is active, False otherwise
def GenerateRandomPassword(self, length=8):
chars = string.ascii_uppercase + string.digits
return ''.join(random.choice(chars) for x in range(8))
# Function: GenerateHashedPassword
# Hash a password using py-bcrypt
#
# Parameters:
# password - The plain text password to hash
#
# Returns:
# A string of the py-bcrypt crypted password
def GenerateHashedPassword(self, password):
return bcrypt.hashpw(password, bcrypt.gensalt())
# Function: CheckPlainTextPassword
# Check a plain-text password against a hashed password.
#
# Parameters:
# password - The plain text password to check
# hashed_password - The stored hashed password to check against.
#
# Returns:
# True if the plain-text password is correct, False otherwise
def CheckPlainTextPassword(self, password, hashed_password):
return bcrypt.hashpw(password, hashed_password) == hashed_password
# Function: GetUserTypeIdFromUserTypeName
# Retrieve the type id from the name of the user type.
#
# Parameters:
# userTypeName - The name of the type of user.
#
# Returns:
# The id of the user type on success, False otherwise.
def GetUserTypeIdFromUserTypeName(self, userTypeName):
cur = self.conn.cursor()
cur.execute("SELECT id FROM user_types WHERE name = %s", (userTypeName,))
result = cur.fetchone()
if result:
(userTypeId,) = result
return userTypeId
return None
# Function: UserLogin
# Log a user into the database (make the user the current user of the database).
#
# Parameters:
# username - The username of the user to login
# password - The password of the user
#
# Returns:
# Returns a User calls object on success (and sets the GenomeDatabase current user), None otherwise.
def UserLogin(self, username, password):
if not self.IsPostgresConnectionActive():
self.ReportError("Unable to establish database connection")
return None
cur = self.conn.cursor()
query = "SELECT id, password, type_id FROM users WHERE username = %s"
cur.execute(query, [username])
result = cur.fetchone()
cur.close()
if result:
(userid, hashed, type_id) = result
if self.CheckPlainTextPassword(password, hashed):
self.currentUser = User(result[0], username, result[2])
return self.currentUser
else:
self.ReportError("Incorrect password")
else:
self.ReportError("User not found")
return None
# Function: CreateUser
# Create a new user for the database.
#
# Parameters:
# username - The username of the user to login
# password - The password of the user (plain-text)
# userTypeId - The id of the type of user to create
#
# Returns:
# True on success, False otherwise.
def CreateUser(self, username, password, userTypeId):
if not self.IsPostgresConnectionActive():
self.ReportError("Unable to establish database connection")
return False
if not self.currentUser:
self.ReportError("You need to be logged in to create a user")
return False
if userTypeId <= self.currentUser.getTypeId():
self.ReportError("Cannot create a user with same or higher level privileges")
return False
cur = self.conn.cursor()
cur.execute("INSERT into users (username, password, type_id) " +
"VALUES (%s, %s, %s) ", (username,
self.GenerateHashedPassword(password),
userTypeId))
self.conn.commit()
return True
# Function: ModifyUser
# Modify the details of a user in the database.
#
# Parameters:
# user_id - The id of the user to change.
# newPassword - The new password (plain-text) of the user.
# userTypeId - The id of the type of user to promote/demote this user to.
#
# Returns:
# True on success, False otherwise.
def ModifyUser(self, user_id, newPassword=None, userTypeId=None):
if not self.IsPostgresConnectionActive():
self.ReportError("Unable to establish database connection.")
return False
if not self.currentUser:
self.ReportError("You need to be logged in to modify a user.")
return False
if not self.CheckForCurrentUserHigherPrivileges(user_id):
if user_id != self.currentUser.getUserId():
self.ReportError("Unable to modify user. User may not exist or you may have insufficient privileges.")
return False
if userTypeId and int(userTypeId) <= self.currentUser.getTypeId():
self.ReportError("Cannot change a user to have the same or higher level privileges as you.")
return False
if userTypeId and user_id == self.currentUser.getUserId():
self.ReportError("You cannot modify your own privileges.")
return False
cur = self.conn.cursor()
query = "SELECT id FROM users WHERE id = %s"
cur.execute(query, [user_id])
result = cur.fetchone()
if not result:
self.ReportError("Unable to find user id: " + user_id)
return False
if newPassword is not None:
if not newPassword:
self.ReportError("You must specify a non-blank password.")
return False
else:
cur.execute("UPDATE users SET password = %s WHERE id = %s",
(self.GenerateHashedPassword(newPassword), user_id))
if userTypeId is not None:
cur.execute("UPDATE users SET type_id = %s WHERE id = %s",
(userTypeId, user_id))
self.conn.commit()
return True
# Function: GetUserIdFromUsername
# Get a user id from a given username.
#
# Parameters:
# username - The username of the user to get an id for.
#
# Returns:
# The id of the user if successful, None on failure.
def GetUserIdFromUsername(self, username):
cur = self.conn.cursor()
cur.execute("SELECT id FROM users WHERE username = %s", (username,))
result = cur.fetchone()
if not result:
self.ReportError("Username not found.")
return None
(user_id,) = result
return user_id
#
# Group: User Permission Functions
#
# Function: CheckForCurrentUserHigherPrivileges
# Checks if the current user is a higher user type than the specified user.
#
# Parameters:
# user_id - The id of the user to compare user types to.
#
# Returns:
# True if the current user is a high user type than the user specified. False otherwise.
def CheckForCurrentUserHigherPrivileges(self, user_id):
"""
Checks if the current user has higher privileges that the specified user_id.
"""
cur = self.conn.cursor()
cur.execute("SELECT type_id FROM users WHERE id = %s", (user_id,))
result = cur.fetchone()
if not result:
self.ReportError("User not found.")
return None
(type_id,) = result
if self.currentUser.getTypeId() < type_id:
return True
else:
return False
# Function: CheckIfRootUser
# Get if the current user is root.
#
# Returns:
# True if current user is root, False otherwise.
def CheckIfRootUser(self):
cur = self.conn.cursor()
cur.execute("SELECT id FROM user_types WHERE name = %s", ('root',));
result = cur.fetchone()
if not result:
raise Exception('GenomeTreeDatabaseException: No Root User in Database!')
return False
(root_id,) = result
if self.currentUser.getTypeId() != root_id:
return False
return True
#
# Group: Genome Management/Query Functions
#
def AddFastaGenome(self, fasta_file, name, desc, id_prefix, source_id=None, id_at_source=None):
cur = self.conn.cursor()
match = re.search('^[A-Z]$', id_prefix)
if not match:
self.ReportError("Tree ID prefixes must be in the range A-Z")
return None
try:
fasta_fh = open(fasta_file, "rb")
except:
self.ReportError("Cannot open Fasta file: " + fasta_file)
return None
fasta_fh.close()
if not self.currentUser:
self.ReportError("You need to be logged in to add a FASTA file.")
return None
query = "SELECT tree_id FROM genomes WHERE tree_id like %s order by tree_id desc;"
cur.execute(query, (id_prefix + '%',))
last_id = None
for (tree_id,) in cur:
last_id = tree_id
break
if (last_id is None):
new_id = id_prefix + "00000001"
else:
new_id = id_prefix + "%08.i" % (int(last_id[1:]) + 1)
if source_id is None:
cur.execute("SELECT id FROM genome_sources WHERE name = 'user'")
result = cur.fetchone()
if not result:
self.ReportError("Could not find 'user' genome source. Possible database corruption.")
return None
(source_id,) = result
if id_at_source is not None:
self.ReportError("You cannot specify an ID at an unspecified genome source.")
return None
if id_at_source is None:
id_at_source = new_id
added = time.mktime(time.localtime()) # Seconds since epoch
initial_xml_string = 'XMLPARSE (DOCUMENT \'<?xml version="1.0"?><data><internal><date_added>%i</date_added></internal></data>\')' % (added)
cur.execute("INSERT INTO genomes (tree_id, name, description, metadata, owner_id, genome_source_id, id_at_source) "
+ "VALUES (%s, %s, %s, " + initial_xml_string + ", %s, %s, %s) "
+ "RETURNING id" , (new_id, name, desc, self.currentUser.getUserId(),
source_id, id_at_source))
genome_id = cur.fetchone()[0]
fasta_oid = self.AddLargeObject(fasta_file)
cur.execute("UPDATE genomes SET genomic_fasta = %s WHERE id = %s",
(fasta_oid, genome_id))
self.conn.commit()
return genome_id
def DeleteGenome(self, genome_id):
cur = self.conn.cursor()
# Check that you are allowed to delete this genome
cur.execute("SELECT owner_id " +
"FROM genomes " +
"WHERE id = %s ", [genome_id])
result = cur.fetchone()
if result is None:
return None
(owner_id,) = result
if (not owner_id == self.currentUser.getUserId()) and not self.CheckForCurrentUserHigherPrivileges(owner_id):
self.lastErrorMessage = "Insufficient priviliges"
return None
# Delete the fasta object
cur.execute("SELECT genomic_fasta " +
"FROM genomes " +
"WHERE id = %s ", [genome_id])
result = cur.fetchone()
if result is not None:
(genomic_oid,) = result
if genomic_oid is not None:
self.DeleteLargeObject(genomic_oid)
# Delete the DB entries object
cur.execute("DELETE from genome_list_contents " +
"WHERE genome_id = %s", [genome_id])
cur.execute("DELETE from aligned_markers " +
"WHERE genome_id = %s", [genome_id])
cur.execute("DELETE from genomes " +
"WHERE id = %s", [genome_id])
self.conn.commit()
return True
def CheckGenomeExists(self, genome_id):
cur = self.conn.cursor()
cur.execute("SELECT id " +
"FROM genomes " +
"WHERE id = %s ", [genome_id])
if cur.fetchone():
return True
else:
return False
def GetGenomeInfo(self, genome_id):
cur = self.conn.cursor()
cur.execute("SELECT tree_id, name, description, owner_id " +
"FROM genomes " +
"WHERE id = %s ", [genome_id])
result = cur.fetchone()
if not result:
self.ReportError("Unable to find genome_id: " + genome_id )
return None
return result
def GetGenomeOwner(self, genome_id):
(tree_id, name, description, owner_id) = self.GetGenomeInfo(genome_id)
return owner_id
def GetGenomeId(self, id_at_source, source_id=None):
"""
If source is None, assume tree_ids.
"""
cur = self.conn.cursor()
return_id = None
if source_id is None:
cur.execute("SELECT id " +
"FROM genomes " +
"WHERE tree_id = %s ", [id_at_source])
result = cur.fetchone()
if result is None:
self.ReportError("Unable to find tree id: " + id_at_source)
return None
(genome_id, ) = result
return genome_id
else:
cur.execute("SELECT id " +
"FROM genomes " +
"WHERE id_at_source = %s " +
"AND genome_source_id = %s", [id_at_source, source_id])
result = cur.fetchone()
if result is None:
self.ReportError("Unable to find genome : " + str(source_id))
return None
(genome_id, ) = result
return genome_id
def SearchGenomes(self, tree_id=None, name=None, description=None, genome_list_id=None, owner_id=None):
cur = self.conn.cursor()
if genome_list_id is not None and genome_list_id in self.GetVisibleGenomeLists():
print "No Genomes Found"
return None
search_terms = list()
query_params = list()
if tree_id is not None:
search_terms.append("genomes.tree_id = %s")
query_params.append(tree_id)
if owner_id is not None:
search_terms.append("genomes.owner_id = %s")
query_params.append(owner_id)
if name is not None:
search_terms.append("genomes.name ILIKE %s")
query_params.append('%' + name + '%')
if description is not None:
search_terms.append("genomes.description ILIKE %s")
query_params.append('%' + description + '%')
if genome_list_id is not None:
search_terms.append("genomes.id in (SELECT genome_id FROM genome_list_contents WHERE list_id = %s)")
query_params.append(genome_list_id)
search_query = ''
if len(search_terms):
search_query = ' AND ' + ' AND '.join(search_terms)
cur.execute("SELECT tree_id, name, username, description, XMLSERIALIZE(document metadata as text) " +
"FROM genomes, users " +
"WHERE owner_id = users.id " + search_query, query_params)
result = cur.fetchall()
if len(result) == 0:
print "No Genomes Found"
return None
return_array = []
for (tree_id, name, username, description, xml) in result:
root = et.fromstring(xml)
date_added = root.findall('internal/date_added')
if len(date_added) == 0:
date_added = 'Unknown Date'
else:
date_added = time.strftime('%X %x %Z',
time.localtime(float(date_added[0].text)))
return_array.append((tree_id, name, username, date_added, description))
return return_array
def ExportGenomicFasta(self, genome_id, destfile=None):
cur = self.conn.cursor()
cur.execute("SELECT genomic_fasta " +
"FROM genomes " +
"WHERE id = %s ", [genome_id])
result = cur.fetchone()
if result is None:
return None
(genomic_oid,) = result
fasta_lobject = self.conn.lobject(genomic_oid, 'r')
if destfile is None:
return fasta_lobject.read()
else:
fasta_lobject.export(destfile)
return True
#
# Group: Genome List Management/Query Functions
#
# Function: CreateGenomeList
# Creates a new genome list in the database
#
# Parameters:
# genome_id_list - A list of genome ids to add to the new list.
# name - The name of the newly created list.
# description - A description of the newly created list.
# owner_id - The id of the user who will own this list.
# private - Bool that denotes whether this list is public or private.
#
# Returns:
# The genome list id of the newly created list.
def CreateGenomeList(self, genome_id_list, name, description, owner_id, private):
cur = self.conn.cursor()
query = "INSERT INTO genome_lists (name, description, owner_id, private) VALUES (%s, %s, %s, %s) RETURNING id"
cur.execute(query, (name, description, owner_id, private))
(genome_list_id, ) = cur.fetchone()
query = "INSERT INTO genome_list_contents (list_id, genome_id) VALUES (%s, %s)"
cur.executemany(query, [(genome_list_id, x) for x in genome_id_list])
self.conn.commit()
return genome_list_id
# Function: CloneGenomeList
# Creates a new genome list by cloning an existing genome list.
#
# Parameters:
# genome_list_id - The genome list id of the genome list to clone.
# name - The name of the cloned genome list.
# description - A description of the cloned genome list.
# owner_id - The id of the user who will own the cloned list.
# private - Bool that denotes whether the cloned list is public or private.
#
# Returns:
# The genome list id of the cloned list.
def CloneGenomeList(self, genome_list_id, name, description, owner_id, private):
cur = self.conn.cursor()
query = "SELECT genome_id FROM genome_list_contents WHERE genome_list_id = %s"
cur.execute(query, (genome_list_id,))
genome_id_list = [x[0] for x in cur.fetchall()]
return self.CreateGenomeList(genome_id_list, name, description, owner_id, private)
# Function: ModifyGenomeList
# Modify the details or contents of an existing genome list.
#
# Parameters:
# genome_list_id - The genome list id of the genome list to modify.
# name - If not None, update the genome list's name to this.
# description - If not None, update the genome list's description to this.
# genome_ids - List of genome id that will modify the contents of the genome list (see operation parameter)
# operation - Perform this operation on the genome ids given in the genome_ids parameter with respect to the genome list (options: add, remove)
# private - If not True, change if this list is private.
#
# Returns:
# True on success, False otherwise.
def ModifyGenomeList(self, genome_list_id, name=None, description=None, genome_ids=None,
operation=None, private=None):
cur = self.conn.cursor()
query = "SELECT owner_id FROM genome_lists WHERE id = %s";
cur.execute(query, (genome_list_id,))
result = cur.fetchone()
if not result:
self.ReportError("Cant find specified Genome List Id: " + str(genome_list_id))
return False
(owner_id, ) = result
# Need to check permissions to edit this list.
if not(self.CheckForCurrentUserHigherPrivileges(owner_id) or owner_id == self.currentUser.getUserId()):
self.ReportError("Insufficient privileges to edit this list")
return False
if name is not None:
query = "UPDATE genome_lists SET name = %s WHERE id = %s";
cur.execute(query, (name, genome_list_id))
if description is not None:
query = "UPDATE genome_lists SET description = %s WHERE id = %s";
cur.execute(query, (description, genome_list_id))
if private is not None:
query = "UPDATE genome_lists SET private = %s WHERE id = %s";
cur.execute(query, (private, genome_list_id))
temp_table_name = "TEMP" + str(int(time.time()))
if genome_ids:
cur.execute("CREATE TEMP TABLE %s (id integer)" % (temp_table_name,) )
query = "INSERT INTO {0} (id) VALUES (%s)".format(temp_table_name)
cur.executemany(query, [(x,) for x in genome_ids])
if operation == 'add':
query = ("INSERT INTO genome_list_contents (list_id, genome_id) " +
"SELECT %s, id FROM {0} " +
"WHERE id NOT IN ( " +
"SELECT genome_id " +
"FROM genome_list_contents " +
"WHERE list_id = %s)").format(temp_table_name)
cur.execute(query, (genome_list_id, genome_list_id))
elif operation == 'remove':
query = ("DELETE FROM genome_list_contents " +
"WHERE list_id = %s " +
"AND genome_id IN ( " +
"SELECT id " +
"FROM {0})").format(temp_table_name)
cur.execute(query, [genome_list_id])
self.conn.commit()
return True
# Function: DeleteGenomeList
# Checks if the current user can delete genome list, and if both allowed and requested, carry out this task.
#
# Parameters:
# genome_list_id - The genome list id of the genome list to delete.
# execute - If False, simply check if the list can be deleted. If True, carry out the check and then delete the list (if permitted).
#
# Returns:
# If execute is False, returns True if the list can be deleted, False otherwise.
# If execute is True, returns True on successful deletion, False otherwise.
def DeleteGenomeList(self, genome_list_id, execute):
"""
Delete a genome list by providing a genome list id. The second parameter, execute,
is a boolean which specifies whether to actually carry out the deletion, or mearly
check if it can be done. This allows the prompting of the user for confirmation to
be handled outside the backend and thus is implementation agnostic.
"""
cur = self.conn.cursor()
query = "SELECT owner_id FROM genome_lists WHERE id = %s"
cur.execute(query, (genome_list_id,))
result = cur.fetchone()
if not result:
self.ReportError("Cant find specified Genome List Id: " + str(genome_list_id) + "\n")
return False
(owner_id,) = result
# Check that we have permission to delete this list.
if (not self.CheckForCurrentUserHigherPrivileges(owner_id)) and (not (owner_id == self.currentUser.getUserId())):
self.ReportError("Insufficient privileges to delete this list: " + str(genome_list_id) + "\n")
return False
if not execute:
return True
query = "DELETE FROM genome_list_contents WHERE list_id = %s"
cur.execute(query, (genome_list_id,))
query = "DELETE FROM genome_lists WHERE id = %s"
cur.execute(query, (genome_list_id,))
self.conn.commit()
return True
# Function: GetGenomeIdListFromGenomeListId
# Given a genome list id, return all the ids of the genomes contained within that genome list.
#
# Parameters:
# genome_list_id - The genome list id of the genome list whose contents needs to be retrieved.
#
# Returns:
# A list of all the genome ids contained within the specified genome list, None on failure.
def GetGenomeIdListFromGenomeListId(self, genome_list_id):
cur = self.conn.cursor()
cur.execute("SELECT id " +
"FROM genome_lists " +
"WHERE id = %s", (genome_list_id,))
if not cur.fetchone():
self.ReportError("No genome list with id: " + str(genome_list_id))
return None
cur.execute("SELECT genome_id " +
"FROM genome_list_contents " +
"WHERE list_id = %s", (genome_list_id,))
result = cur.fetchall()
return [genome_id for (genome_id,) in result]
# Function: GetVisibleGenomeLists
# Get all genome list owned by the specified owner which the current user is allowed to see.
#
# Parameters:
# owner_id - Get visible genome lists owned by this user with this id. If not specified, get all visible lists.
#
# Returns:
# A list containing a tuple for each visible genome list. The tuple contains the genome list id, genome list name, genome list description,
# and username of the owner of the list (id, name, description, username).
def GetVisibleGenomeLists(self, owner_id=None):
"""
Get all genome list owned by owner_id which the current user is allowed
to see. If owner_id is None, return all visible genome lists for the
current user.
"""
cur = self.conn.cursor()
if owner_id is None:
cur.execute("SELECT list.id, list.name, list.description, username " +
"FROM genome_lists as list, users " +
"WHERE list.owner_id = users.id " +
"AND (list.private = False " +
"OR users.type_id > %s " +
"OR list.owner_id = %s) " +
"ORDER by list.id ", (self.currentUser.getTypeId(),
self.currentUser.getUserId()))
else:
cur.execute("SELECT list.id, list.name, list.description, username " +
"FROM genome_lists as list, users " +
"WHERE list.owner_id = users.id " +
"AND list.owner_id = %s " +
"ORDER by list.id ", (self.currentUser.getUserId(),))
return cur.fetchall()
#
# Group: Marker Management Functions
#
def AddMarkers(self, hmm_file, database_id, use_existing=False):
cur = self.conn.cursor()
if not self.CheckIfRootUser():
self.lastErrorMessage = "Only root can do that."
return False
try:
mp = HmmModelParser(hmm_file)
added_oids = list()
added_marker_ids = list()
for model in mp.parse():
splitdate = model.date.split()
postgres_date = "%s %s" % ("-".join([splitdate[1], splitdate[2], splitdate[4]]), splitdate[3])
try:
model.acc
except AttributeError:
model.acc = model.name
try:
model.desc
except AttributeError:
model.desc = model.name
tmpoutfile = tempfile.NamedTemporaryFile(delete=False)
tmpoutfile.write(str(model))
tmpoutfile.close()
cur.execute("SELECT id, database_specific_id, timestamp, name "+
"FROM markers "+
"WHERE database_specific_id = %s " +
"AND timestamp = %s " +
"AND database_id = %s", (model.acc, postgres_date, database_id))
result = cur.fetchone()
if result:
(marker_id, database_specific_id, timestamp, name) = result
if use_existing:
added_marker_ids.append(marker_id)
sys.stderr.write("%s already exists in database, using existing marker\n" % (database_specific_id,))
else:
self.lastErrorMessage = "Marker '%s' already exists in database, use --use_existing flag to ignore" % (database_specific_id,)
return False
else:
cur.execute("INSERT into markers (database_specific_id, name, size, database_id, timestamp) "+
"VALUES (%s, %s, %s, %s, %s) "+
"RETURNING id", (model.acc, model.desc, model.leng, database_id, postgres_date))
marker_id = cur.fetchone()[0]
added_marker_ids.append(marker_id)
marker_lobject = self.conn.lobject(0, 'w', 0, tmpoutfile.name)
cur.execute("UPDATE markers SET hmm = %s WHERE id = %s",
(marker_lobject.oid, marker_id))