This repository was archived by the owner on Sep 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRssDB.py
More file actions
2784 lines (2509 loc) · 150 KB
/
RssDB.py
File metadata and controls
2784 lines (2509 loc) · 150 KB
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
"""Database connection classes for rssDB
implemented database products:
- Sqlite
- Postgresql
- MongoDB
"""
import sys, os, re, time, glob, io, json, gettext, gc, tempfile, logging, calendar, concurrent.futures, threading, traceback, pickle
from math import isnan, isinf
from decimal import Decimal
from tkinter.filedialog import SaveAs
from concurrent.futures import as_completed
from collections import OrderedDict
from datetime import datetime, date, timedelta
from dateutil import parser, tz
from calendar import monthrange
from lxml import html, etree
from urllib import request
from arelle import ModelXbrl, XmlUtil
from arelle.PythonUtil import flattenSequence
from arelle.CntlrCmdLine import CntlrCmdLine
from .Constants import pathToSQL, wait_duration, DBTypes, rssTables, rssCols, RSSFEEDS
from .CommonFunctions import updateCikTickerMapping, _populateFilersInfo, _doAll,\
getFilerInformation, _getMonthlyFeedsLinks, _getFeedInfo, getRssItemInfo, _startDBReport
try:
from xbrlDB.SqlDb import SqlDbConnection, XPDBException, pg8000
except:
try:
from arelle.plugin.xbrlDB.SqlDb import SqlDbConnection, XPDBException, pg8000
except:
from plugin.xbrlDB.SqlDb import SqlDbConnection, XPDBException, pg8000
try:
from arellepy.HelperFuncs import chkToList, convert_size, xmlFileFromString
from arellepy.CntlrPy import CntlrPy, subProcessCntlrPy, renderEdgarReportsFromRssItems
from arellepy.LocalViewerStandalone import initViewer
except:
from .arellepy.HelperFuncs import chkToList, convert_size, xmlFileFromString
from .arellepy.CntlrPy import CntlrPy, subProcessCntlrPy, renderEdgarReportsFromRssItems
from .arellepy.LocalViewerStandalone import initViewer
hasMongoDB = True
try:
from pymongo import MongoClient, ASCENDING, DESCENDING
except Exception as e:
hasMongoDB = False
TRACESQLFILE = None
sqlScriptsFiles = {
'sqlite': ['sqliteCreateRssDB.sql', 'industryClassificationDataInsert.sql'],
'postgres': ['postgreCreateRssDB.sql', 'industryClassificationDataInsert.sql']
}
mongodbSchemaFile = os.path.join(pathToSQL, 'mongodbSchema.json')
mongodbIndustryClassificationFile = os.path.join(pathToSQL, 'mongodbIndustryClassification.json')
MAKEDOTS_RSSDB = False
def dotted(cntlr, xtext='Processing'):
'''Just let me know you are alive!'''
global MAKEDOTS_RSSDB
n = 1
while MAKEDOTS_RSSDB:
_xtext = xtext + '.'*n
cntlr.waitForUiThreadQueue()
cntlr.uiThreadQueue.put((cntlr.showStatus,[_xtext]))
if n >=15:
n = 1
else:
n+=1
time.sleep(.8)
cntlr.waitForUiThreadQueue()
cntlr.uiThreadQueue.put((cntlr.showStatus,['']))
return
def rssDBConnection(cntlr, **kwargs):
'''Shortcut to connect to db, returns connection object of the appropriate type
kwargs:
user: database user name, not relevant to sqlite
password: database password, not relevant to sqlite
host: localhost or computer hosing the database, not relevant to sqlite
port: int for port number on host
database: database name
timeout: time out for trying to connect
product: one of 'postgres', 'sqlite', 'mongodb'
schema: in case of postgres a schema must to be provided
createSchema: in case of prostgres, whether to create a schema and tables (initialize tables)
createDB: whether to create database and tables, not relevant to postgres
'''
gettext.install('arelle')
# cntlr.addToLog('Platform :{} Platform: {} GUI: {}'.format(sys.platform.lower().startswith('win'), sys.platform.lower(), cntlr.hasGui) )
global hasMongoDB, MongoClient, ASCENDING, DESCENDING
if not kwargs.get('product') in DBTypes:
raise Exception('product must be on of {} {} was entered'.format(', '.join(DBTypes), kwargs.get('product')))
conParams = {
'user': kwargs.get('user', None),
'password': kwargs.get('password', None), 'host': kwargs.get('host', None),
'port': kwargs.get('port', None), 'database': kwargs.get('database', None),
'timeout': kwargs.get('timeout', None), 'product': kwargs.get('product', None), 'schema': kwargs.get('schema', None),
'createSchema': kwargs.get('createSchema', None), 'createDB': kwargs.get('createDB', None),
}
dbConn = None
if kwargs.get('product') in ('postgres', 'sqlite'):
dbConn = rssSqlDbConnection(cntlr, **conParams)
elif kwargs.get('product') == 'mongodb':
# check if required packages exists
# first make sure that additional path entries in config file are added
rssDBaddToSysPath = cntlr.config.setdefault('rssDBaddToSysPath', [])
for p in rssDBaddToSysPath:
if not p in sys.path:
sys.path.append(p)
try:
from pymongo import MongoClient, ASCENDING, DESCENDING
hasMongoDB = True
except Exception as e:
hasMongoDB = False
pyMongoPath = []
fail_msg = _("No path was provided")
fail_msg_2 = _('pymongo package required to use this feature is not available')
if not hasMongoDB:
if cntlr.hasGui:
from tkinter import filedialog
from tkinter import messagebox
getpath = messagebox.askyesno(
title=(_('RSS DB Connection Error')),
message = ('pymongo package needed for mongodb connection is not avaliable '
'in the current installation of arelle.\n\n'
'Do you want to add an installed pymongo to path? Must be for python {}.{}').format(sys.version_info.major, sys.version_info.minor),
icon='warning', parent=cntlr.parent)
if getpath:
pyMongoPath = filedialog.askdirectory(title=_('Select pymongo installation dir'), parent=cntlr.parent)
if pyMongoPath and os.path.isdir(pyMongoPath):
if not pyMongoPath in sys.path:
sys.path.append(pyMongoPath)
else:
cntlr.addToLog(fail_msg, messageCode="RssDB.Info", file="", level=logging.INFO)
messagebox.showinfo(title=_("RSS DB Info"), message=fail_msg, parent=cntlr.parent)
return
try:
from pymongo import MongoClient, ASCENDING, DESCENDING
hasMongoDB = True
_pyMongoPath = chkToList(pyMongoPath, str)
for p in _pyMongoPath:
if p not in rssDBaddToSysPath:
rssDBaddToSysPath.append(p)
cntlr.saveConfig()
except Exception as e:
hasMongoDB = False
cntlr.addToLog(fail_msg_2, messageCode="RssDB.Error", file="", level=logging.ERROR)
messagebox.showinfo(title=_("RSS DB Info"), message=fail_msg_2 +'\n'+str(e), parent=cntlr.parent)
else:
cntlr.addToLog(fail_msg, messageCode="RssDB.Info", file="", level=logging.INFO)
messagebox.showinfo(title=_("RSS DB Info"), message=fail_msg, parent=cntlr.parent)
return
else:
cntlr.addToLog(fail_msg_2, messageCode="RssDB.Error", file="", level=logging.ERROR)
cntlr.showStatus(_('Install required packages or add installation path to "sys.path"'))
return
dbConn = rssMongoDbConnection(cntlr, **conParams)
return dbConn
def _getFeedInfoHelper(setConfigDir, targetResDir, conParams, feedLink, lastModifiedDate, isNew, product,
insertIntoDB=False, reloadCache=False, getFiles=True, getXML=False, returnInfo=False, isLatest=False, q=None):
"""helper function for concurrent executor gets feed info ready to insert in db"""
import gettext, datetime, time
conn = None
cntlr = None
startAllTime = time.perf_counter()
cntlr = subProcessCntlrPy(
instConfigDir=setConfigDir,
useResDir=targetResDir,
logFileName="logToBuffer",
loadPlugins=False,
q=q
)
conParams['cntlr'] = cntlr
conn = None
if product in ('sqlite', 'postgres'):
conn = rssSqlDbConnection(**conParams)
elif product == 'mongodb':
conn = rssMongoDbConnection(**conParams)
if isLatest:
conn.showStatus(_('Getting Latest Filings'))
info = conn.getFeedInfo(feedLink, lastModifiedDate, isNew, reloadCache, getFiles, getXML)
flatenFiles = []
if len(info[rssTables[2]])>0:
flatenFiles = [y for x in info[rssTables[2]] for y in x]
info[rssTables[2]] = flatenFiles
insertUpdateStats = {x:{'insert':0, 'update':0} for x in rssTables}
_feedInfo = dict()
if isLatest: # do not re-insert feedsInfo entry if it exists
feedsIds = conn.getExistingFeeds()
if info[rssTables[0]][rssCols[rssTables[0]][0]] in feedsIds:
_feedInfo = info.pop(rssTables[0])
_feedInfo['Status'] = 'Month feed already in DB'
# but ensure stats reflects this feed was updated
insertUpdateStats[rssTables[0]]['update'] = 1 if any([len(v) for k, v in info.items() if k in rssTables]) else 0
else:
# in case of first day of the month before the monthly page is updated
info['isNew'] = True
if insertIntoDB:
_action='update' if not info['isNew'] else 'insert'
try:
if isLatest:
conn.showStatus(_('Inserting Latest Filings'))
for _tbl, data in info.items():
if _tbl in rssTables and len(data)>0:
insertUpdateStats[_tbl] = conn.insertUpdateRssDB(data, _tbl, _action if _tbl == rssTables[0] else 'insert' , returnStat=True)
if conn.product in ['sqlite', 'postgres']:
conn.commit()
except Exception as e:
if conn.product in ['sqlite', 'postgres']:
conn.rollback()
raise e
if isLatest and _feedInfo:
info[rssTables[0]] = _feedInfo
_feed = {rssTables[0]: info[rssTables[0]]} if isLatest else None
results = {'link': feedLink,'stat': insertUpdateStats, 'feed': _feed}
results['logMsg'] = _("Finished extracting data and inserting into db {} secs").format(round(time.perf_counter() - startAllTime, 3))
conn.addToLog(results['logMsg'], messageCode="RssDB.Info", file=feedLink, level=logging.INFO)
if returnInfo:
results['feed'] = info
else:
del flatenFiles
del info
try:
logs = cntlr.logHandler.getLines()
except:
pass
cntlr.modelManager.close()
del cntlr, conParams, conn
gc.collect()
return results
def _updateRssFeeds(conn, loc=None, getRssItems=False, updateDB=False, maxWorkers=None, returnInfo=False,
dateFrom=None, dateTo=None, last=None, reloadCache=False, includeLatest=False, getFiles=True, getXML=False, q=None):
"""Checks for new feeds and rss items, initializes and/or updates rss DB tables if specified"""
global MAKEDOTS_RSSDB
if not maxWorkers:
# use half of available cpus
maxWorkers = os.cpu_count()/2
conParams = conn.conParams
startTime = time.perf_counter()
links = conn.getMonthlyFeedsLinks(loc=loc, maxWorkers=maxWorkers, last=last, dateFrom=dateFrom, dateTo=dateTo)
feeds = []
if getRssItems:
setConfigDir = os.path.dirname(conn.cntlr.userAppDir)
targetResDir = os.path.dirname(conn.cntlr.imagesDir)
if updateDB:
# make sure tables/schema are created
if conn.product == 'mongodb':
conn.verifyCollections(createCollections=True)
else:
conn.verifyTables(createTables=True)
if sys.platform.lower().startswith('win'):
# then we are in windows world
conn.addToLog(_('Not using multiprocessing for extracting feed data'), messageCode="RssDB.Info", file=conn.conParams.get('database',''), level=logging.INFO)
if conn.cntlr.hasGui:
MAKEDOTS_RSSDB = True
t = threading.Thread(target=dotted, args=(conn.cntlr,), daemon=True)
t.start()
_links = [(x['link'], x.get('lastModifiedDate', None), x.get('isNew', None)) for x in links]
for l, d, n in _links:
res = _getFeedInfoHelper(setConfigDir, targetResDir, conParams, l, d, n, conn.product, updateDB, reloadCache, getFiles, getXML, returnInfo, False, q)
feeds.append(res)
conn.addToLog(res['logMsg'], messageCode="RssDB.Info", file=l, level=logging.INFO)
latest = None
if includeLatest:
latest = _getFeedInfoHelper(setConfigDir, targetResDir, conParams, RSSFEEDS['US SEC All Filings'], datetime.min, False, conn.product, updateDB,
reloadCache, getFiles, getXML, returnInfo, True, q)
conn.addToLog('Latest: ' + latest['logMsg'], messageCode="RssDB.Info", file=RSSFEEDS['US SEC All Filings'], level=logging.INFO)
feeds.append(latest)
if latest:
latestLink = {'feedId': latest['feed']['feedsInfo'].get('feedId'),
'feedDate': latest['feed']['feedsInfo'].get('feedMonth'),
'link': latest['feed']['feedsInfo'].get('link'),
'lastModifiedDate': None,
'lastBuildDate': latest['feed']['feedsInfo']['lastBuildDate'],
'isNew': False
}
links.append(latestLink)
else:
conn.addToLog(_('Using multiprocessing for extracting feed data with maxWorkers: {}').format(maxWorkers), messageCode="RssDB.Info",
file=conn.conParams.get('database',''), level=logging.INFO)
with concurrent.futures.ProcessPoolExecutor(max_workers=int(maxWorkers)) as executor:
argLen = len(links)
a1 = [setConfigDir] * argLen
a2 = [targetResDir] * argLen
a3 = [conParams] * argLen
a4 = [x['link'] for x in links]
a5 = [x['lastModifiedDate'] if 'lastModifiedDate' in x.keys() else None for x in links]
a6 = [x['isNew'] for x in links]
a7 = [conn.product] * argLen
a8 = [updateDB] * argLen
a9 = [reloadCache] * argLen
a10 = [getFiles] * argLen
a11 = [getXML] * argLen
a12 = [returnInfo] * argLen
a13 = [False] * argLen
# _feeds = executor.map(_getFeedInfoHelper, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, [q] * argLen)
argZ = zip(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, [q] * argLen)
__feeds = [executor.submit(_getFeedInfoHelper, *x) for x in zip(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, [None] * argLen) ]
_feeds = []
if conn.cntlr.hasGui:
MAKEDOTS_RSSDB = True
t = threading.Thread(target=dotted, args=(conn.cntlr,), daemon=True)
t.start()
for x in as_completed(__feeds):
conn.addToLog(x.result()['logMsg'], messageCode="RssDB.Info", file=x.result()['link'], level=logging.INFO)
_feeds.append(x.result())
feeds = list(_feeds)
latest = None
if includeLatest:
_latest = executor.submit(_getFeedInfoHelper, setConfigDir, targetResDir, conParams, RSSFEEDS['US SEC All Filings'],
datetime.min, False, conn.product, updateDB,
reloadCache, getFiles, getXML, returnInfo, True, None)
latest = _latest.result()
conn.addToLog('Latest: ' + latest['logMsg'], messageCode="RssDB.Info", file=RSSFEEDS['US SEC All Filings'], level=logging.INFO)
feeds.append(latest)
if latest:
latestLink = {'feedId': latest['feed']['feedsInfo'].get('feedId'),
'feedDate': latest['feed']['feedsInfo'].get('feedMonth'),
'link': latest['feed']['feedsInfo'].get('link'),
'lastModifiedDate': None,
'lastBuildDate': latest['feed']['feedsInfo']['lastBuildDate'],
'isNew': False
}
links.append(latestLink)
if MAKEDOTS_RSSDB:
MAKEDOTS_RSSDB = False
summaryList = [x['stat'] for x in feeds]
summaryTotals = dict()
for t in rssTables:
updates = []
inserts = []
for s in summaryList:
if s[t].get('update'):
updates.append(s[t].get('update'))
if s[t].get('insert'):
inserts.append(s[t].get('insert'))
summaryTotals[t] = {'insert': sum(inserts), 'update': sum(updates)}
_msg = _('Finished updating RSS Feeds in {} secs').format(round(time.perf_counter()-startTime, 3),
messageCode="RssDB.Info", file="", level=logging.INFO)
result = {'summary': summaryTotals, 'stats': _msg}
if returnInfo:
result['links'] = links
result['feeds'] = [x['feed'] for x in feeds if x['feed']]
else:
del feeds, links
conn.addToLog(_msg, messageCode="RssDB.Info", file=conn.conParams.get('database',''), level=logging.INFO)
return result
class rssSqlDbConnection(SqlDbConnection):
"""Few modifications to sqlDBConnection class"""
def __init__(self, cntlr, user, password, host, port, database, timeout, product, schema, createSchema=False, createDB=False):
self.cntlr = cntlr
self.autoUpdateSet = False
self.updateStarted = False
self.updateStopped = False
_modelXbrl = cntlr.modelManager.modelXbrl
if not _modelXbrl:
_modelXbrl = ModelXbrl.ModelXbrl(cntlr.modelManager)
if createDB:
if product == 'postgres':
self.addToLog(_('Cannot create database on postgres can only create schema, database needs to be created on the server'), messageCode="RssDB.Error", file=database, level=logging.ERROR)
raise Exception('Cannot create database on postgres, can only create schema, database needs to be created on the server')
elif not createDB and product == 'sqlite' and not database == ':memory:':
if not os.path.exists(database):
self.addToLog(_('Database "{}" does not Exist').format(database), messageCode="RssDB.Error", file=database, level=logging.ERROR)
raise Exception('Database "{}" does not Exist'.format(database))
self.conParams = {'cntlr': None, 'user': user,
'password': password, 'host': host,
'port': port, 'database': database,
'timeout': timeout, 'product': product, 'schema': schema}
super().__init__(_modelXbrl, user, password, host, port, database, timeout, product)
if self.product in ['postgres']:
if not schema:
schema = 'rssFeeds'
try:
_schemas = self.execute('select schema_name from information_schema.schemata;', fetch=True)
schemas = [s[0] for s in _schemas]
if not schema in schemas:
if createSchema:
stat = _('Creating Schema {}').format(schema)
self.showStatus(stat, 2000)
self.execute('CREATE SCHEMA IF NOT EXISTS "{}";'.format(
schema), action=stat, fetch=False, commit=True)
else:
raise Exception('Schama {} does not exist in {} database'.format(schema, database))
self.execute('SET search_path = "{}";'.format(schema), fetch=False, commit=True)
self.showStatus(_('Path set to {}').format(schema), 2000)
except Exception as e:
self.rollback()
raise e
self.schema = schema
self.conParams['schema'] = schema
if product=='postgres' and createSchema:
chkTables = self.verifyTables(createTables=False, dropPriorTables=False)
if not chkTables:
self.create([os.path.join(pathToSQL, f) for f in sqlScriptsFiles[self.product]], dropPriorTables=False)
if product == 'sqlite' and createDB:
chkTables = self.verifyTables(createTables=False, dropPriorTables=False)
if not chkTables:
self.create([os.path.join(pathToSQL, f) for f in sqlScriptsFiles[self.product]], dropPriorTables=False)
chk = self.checkConnection()
if not chk:
self.close()
raise Exception('Could not connet to database {}'.format(database))
return
def getFormulae(self):
qry = self.execute('select "formulaId", "description", "fileName", "dateTimeAdded" from formulae', fetch=True, close=False)
cols = [x[0].decode() if type(x[0]) is bytes else x[0] for x in self.cursor.description]
res = [dict(zip(cols, x) )for x in qry]
return res
def dbTableNameStr(self, tableName):
if self.product == "postgres":
return '"' + tableName + '"'
else:
return tableName
def _getTable(self, table, idCol, newCols=None, matchCols=None, data=None, commit=False,
comparisonOperator='=', checkIfExisting=False, insertIfNotMatched=True,
returnMatches=True, returnExistenceStatus=False):
'''Modified to accommodate camel case table/col name + only keeps pg and sqlite'''
# generate SQL
# note: comparison by = will never match NULL fields
# use 'IS NOT DISTINCT FROM' to match nulls, but this is not indexed and verrrrry slooooow
if not data or not newCols or not matchCols:
# nothing can be done, just return
return () # place breakpoint here to debug
isPostgres = self.product == "postgres"
isSQLite = self.product == "sqlite"
newCols = [newCol.lower() if isSQLite else newCol for newCol in newCols]
matchCols = [matchCol.lower() if isSQLite else matchCol for matchCol in matchCols]
returningCols = []
if idCol: # idCol is the first returned column if present
returningCols.append(idCol)
for matchCol in matchCols:
if matchCol not in returningCols: # allow idCol to be specified or default assigned
returningCols.append(matchCol)
colTypeFunctions = self.columnTypeFunctions(table)
colDeclarations = self.tableColDeclaration.get(table)
try:
colTypeCast = tuple(colTypeFunctions[colName][0] for colName in newCols)
colTypeFunction = [colTypeFunctions[colName][1] for colName in returningCols]
if returnExistenceStatus:
colTypeFunction.append(self.pyBoolFromDbBool) # existence is a boolean
except KeyError as err:
raise XPDBException("xpgDB:MissingColumnDefinition",
_("Table %(table)s column definition missing: %(missingColumnName)s"),
table=table, missingColumnName=str(err))
rowValues = []
rowLongValues = [] # contains None if no parameters, else {} parameter dict
longColValues = []
for row in data:
colValues = []
for col in row:
if isinstance(col, bool):
if isSQLite:
colValues.append('1' if col else '0')
else:
colValues.append('TRUE' if col else 'FALSE')
elif isinstance(col, int):
colValues.append(str(col))
elif isinstance(col, float):
if _ISFINITE(col):
colValues.append(str(col))
else: # no NaN, INF, in SQL implementations (Postgres has it but not IEEE implementation)
colValues.append('NULL')
elif isinstance(col, Decimal):
if col.is_finite():
colValues.append(str(col))
else: # no NaN, INF, in SQL implementations (Postgres has it but not IEEE implementation)
colValues.append('NULL')
elif isinstance(col, datetime) and isSQLite:
colValues.append("'{:04}-{:02}-{:02} {:02}:{:02}:{:02}'".format(col.year, col.month, col.day, col.hour, col.minute, col.second))
elif isinstance(col, datetime) and isSQLite:
colValues.append("'{:04}-{:02}-{:02}'".format(col.year, col.month, col.day))
elif col is None:
colValues.append('NULL')
elif isinstance(col, bytes) and isPostgres:
hexvals = "".join([hex(x)[2:] for x in col])
#get the hex values
hexvals = [hex(x)[2:] for x in col]
#fix up single digit values
for i in range(len(hexvals)):
if len(hexvals[i]) == 1:
hexvals[i] = "0" + hexvals[i]
colValues.append(r"E'\\x" + "".join(hexvals) + "'")
#colValues.append(r"E'\\x" + col.decode() + "'" )
else:
colValues.append(self.dbStr(col))
if not rowValues and isPostgres: # first row
for i, cast in enumerate(colTypeCast):
if cast:
colValues[i] = colValues[i] + cast
rowColValues = ", ".join(colValues)
rowValues.append("(" + rowColValues + ")")
if longColValues:
rowLongValues.append(longColValues)
longColValues = []
else:
rowLongValues.append(None)
values = ", \n".join(rowValues)
_table = self.dbTableNameStr(table)
_inputTableName = self.tempInputTableName
if self.product == "postgres":
newCols = [self.dbTableNameStr(c) for c in newCols]
returningCols = [self.dbTableNameStr(c) for c in returningCols]
# insert new rows, return id and cols of new and existing rows
# use IS NOT DISTINCT FROM instead of = to compare NULL usefully
sql = [(('''
WITH row_values (%(newCols)s) AS (
VALUES %(values)s
)''' + (''', insertions AS (
INSERT INTO %(table)s (%(newCols)s)
SELECT %(newCols)s
FROM row_values v''' + ('''
WHERE NOT EXISTS (SELECT 1
FROM %(table)s x
WHERE %(match)s)''' if checkIfExisting else '') + '''
RETURNING %(returningCols)s
) ''' if insertIfNotMatched else '') + '''
(''' + (('''
SELECT %(x_returningCols)s %(statusIfExisting)s
FROM %(table)s x JOIN row_values v ON (%(match)s) ''' if checkIfExisting else '') + ('''
) UNION ( ''' if (checkIfExisting and insertIfNotMatched) else '') + ('''
SELECT %(returningCols)s %(statusIfInserted)s
FROM insertions''' if insertIfNotMatched else '')) + '''
);''') % {"table": _table,
"idCol": idCol,
"newCols": ', '.join(newCols),
"returningCols": ', '.join(returningCols),
"x_returningCols": ', '.join('x.{0}'.format(c) for c in returningCols),
"match": ' AND '.join('x.{0} {1} v.{0}'.format(col, comparisonOperator)
for col in matchCols),
"values": values,
"statusIfInserted": ", FALSE" if returnExistenceStatus else "",
"statusIfExisting": ", TRUE" if returnExistenceStatus else ""
}, None, True)]
elif self.product == "sqlite":
sql = [("CREATE TEMP TABLE %(inputTable)s ( %(inputCols)s );" %
{"inputTable": _inputTableName,
"inputCols": ', '.join('{0} {1}'.format(newCol, colDeclarations[newCol])
for newCol in newCols)}, None, False)]
# break values insertion into 1000's each
def insertSQLiteRows(i, j, params):
sql.append(("INSERT INTO %(inputTable)s ( %(newCols)s ) VALUES %(values)s;" %
{"inputTable": _inputTableName,
"newCols": ', '.join(newCols),
"values": ", ".join(rowValues[i:j])}, params, False))
iMax = len(rowValues)
i = 0
while (i < iMax):
for j in range(i, min(i+500, iMax)):
if rowLongValues[j] is not None:
if j > i:
insertSQLiteRows(i, j, None)
insertSQLiteRows(j, j+1, rowLongValues[j])
i = j + 1
break
if i < j+1 and i < iMax:
insertSQLiteRows(i, j+1, None)
i = j+1
if insertIfNotMatched:
if checkIfExisting:
_where = ('WHERE NOT EXISTS (SELECT 1 FROM %(table)s x WHERE %(match)s)' %
{"table": _table,
"match": ' AND '.join('x.{0} {1} i.{0}'.format(col, comparisonOperator)
for col in matchCols)})
else:
_where = ""
sql.append( ("INSERT INTO %(table)s ( %(newCols)s ) SELECT %(newCols)s FROM %(inputTable)s i %(where)s;" %
{"inputTable": _inputTableName,
"table": _table,
"newCols": ', '.join(newCols),
"where": _where}, None, False) )
if returnMatches or returnExistenceStatus:
sql.append(# don't know how to get status if existing
("SELECT %(returningCols)s %(statusIfExisting)s from %(inputTable)s JOIN %(table)s ON ( %(match)s );" %
{"inputTable": _inputTableName,
"table": _table,
"newCols": ', '.join(newCols),
"match": ' AND '.join('{0}.{2} = {1}.{2}'.format(_table,_inputTableName,col)
for col in matchCols),
"statusIfExisting": ", 0" if returnExistenceStatus else "",
"returningCols": ', '.join('{0}.{1}'.format(_table,col)
for col in returningCols)}, None, True))
sql.append(("DROP TABLE %(inputTable)s;" %
{"inputTable": _inputTableName}, None, False))
if insertIfNotMatched and self.syncSequences:
sql.append( ("update sqlite_sequence "
"set seq = (select seq from sqlite_sequence where name = '%(table)s') "
"where name != '%(table)s';" %
{"table": _table}, None, False) )
tableRows = []
for sqlStmt, params, fetch in sql:
result = self.execute(sqlStmt,commit=commit, close=False, fetch=fetch, params=params)
if fetch and result:
tableRows.extend(result)
return tuple(tuple(None if colValue == "NULL" or colValue is None else
colTypeFunction[i](colValue) # convert to int, datetime, etc
for i, colValue in enumerate(row))
for row in tableRows)
def _updateTable(self, table, cols=None, data=None, commit=False):
'''Modified to accommodate camel case table/col name + only keeps pg and sqlite'''
# generate SQL
# note: comparison by = will never match NULL fields
# use 'IS NOT DISTINCT FROM' to match nulls, but this is not indexed and verrrrry slooooow
if not cols or not data:
# nothing can be done, just return
return () # place breakpoint here to debug
isSQLite = self.product == "sqlite"
idCol = cols[0]
colTypeFunctions = self.columnTypeFunctions(table)
colDeclarations = self.tableColDeclaration.get(table)
try:
colTypeCast = tuple(colTypeFunctions[colName.lower() if isSQLite else colName][0] for colName in cols)
except KeyError as err:
raise XPDBException("xpgDB:MissingColumnDefinition",
_("Table %(table)s column definition missing: %(missingColumnName)s"),
table=table, missingColumnName=str(err))
rowValues = []
for row in data:
colValues = []
for col in row:
if isinstance(col, bool):
colValues.append('TRUE' if col else 'FALSE')
elif isinstance(col, (int,float)):
colValues.append(str(col))
elif col is None:
colValues.append('NULL')
else:
colValues.append(self.dbStr(col))
if not rowValues and self.product == "postgres": # first row
for i, cast in enumerate(colTypeCast):
if cast:
colValues[i] = colValues[i] + cast
rowColValues = ", ".join(colValues)
if isSQLite:
rowValues.append(colValues)
else:
rowValues.append("(" + rowColValues + ")")
if not isSQLite:
values = ", \n".join(rowValues)
_table = self.dbTableNameStr(table)
_inputTableName = self.tempInputTableName
if self.product == "postgres":
cols = [self.dbTableNameStr(c) for c in cols]
idCol = self.dbTableNameStr(idCol)
# insert new rows, return id and cols of new and existing rows
# use IS NOT DISTINCT FROM instead of = to compare NULL usefully
sql = [('''
WITH input (%(valCols)s) AS ( VALUES %(values)s )
UPDATE %(table)s t SET %(settings)s
FROM input i WHERE i.%(idCol)s = t.%(idCol)s
;''') % {"table": _table,
"idCol": idCol,
"valCols": ', '.join(col for col in cols),
"settings": ', '.join('{0} = i.{0}'.format(cols[i])
for i, col in enumerate(cols)
if i > 0),
"values": values}]
elif self.product == "sqlite":
sql = ["UPDATE %(table)s SET %(settings)s WHERE %(idCol)s = %(idVal)s;" %
{"table": _table,
"idCol": idCol,
"idVal": rowValue[0],
"settings": ', '.join('{0} = {1}'.format(col,rowValue[i])
for i, col in enumerate(cols)
if i > 0)}
for rowValue in rowValues]
for sqlStmt in sql:
self.execute(sqlStmt,commit=commit, fetch=False, close=False)
def addFormulaToDb(self, fileName=None, formulaId=None, description=None, formulaLinkBaseString=None, replaceExistingFormula=False, returnData=True):
'''Inserts a new or updates existing formula in the database
Cannot have duplicate formulaId OR fileName in db, checks if filename already exists in database, if exists and `replaceExistingFormula` set to False,
file is not added, if `replaceExistingFormula` set to True, the database entry is updated with the current data.
Formula can be read as string via `formulaLinkBaseString` parameter directly, if only filename is provided the file is read from drive.
At least one of fileName or formulaLinkbaseString must be entered.
args:
fileName: path to formula linkbase file on local drive or just a unique name if `formulaLinkBaseString` is used
description: a brief description of what the function does, defaults to file basename
formulaLinkBaseString: Sting representing a valid formula linkbase
replaceExisting: if there is an entry with the same file name in the db, and this parameter is set to true, the existing entry is replace with current data
'''
pgParamStyle = None
if self.product == 'postgres':
pgParamStyle = pg8000.paramstyle
pg8000.paramstyle = 'qmark'
noFile = 'NO_FILE'
if not any([fileName, formulaLinkBaseString]):
self.cntlr.addToLog(_('At least one of fileName or formulaLinkbaseString must be entered.'), messageCode="RssDB.Error", file=self.conParams.get('database',''), level=logging.ERROR)
return
action = 'insert'
formulaData = dict()
if fileName is None:
fileName = noFile
_existingFiles = []
existingFormulaId = []
existingFileNames = []
if any([fileName, formulaId]):
f_qry = 'SELECT "formulaId", "fileName" from "formulae" WHERE '
params = tuple()
if formulaId is None and fileName:
f_qry += '"fileName"=?'
params = (fileName,)
elif fileName is None and formulaId:
f_qry += '"formulaId"=?'
params = (formulaId,)
elif all([fileName, formulaId]):
f_qry += '"formulaId"=? OR "fileName"=?'
params = (formulaId, fileName)
_existingFiles = self.execute(f_qry, params=params, fetch=True)
if _existingFiles:
existingFormulaId = [x for x in _existingFiles if x[0]==formulaId]
existingFileNames = [x for x in _existingFiles if x[1]==fileName]
if existingFormulaId or existingFileNames:
existingIds = [x[0] for x in existingFileNames]
if replaceExistingFormula:
action = 'update'
if not formulaId or formulaId not in existingIds:
self.cntlr.addToLog(_('Enter an existing formulaId to update, existing ids: {}').format(str(existingIds)), messageCode="RssDB.Info", file=self.conParams.get('database',''), level=logging.INFO)
return
else:
idMsg = 'formula with formulaId {}'.format(str(formulaId)) if len(existingFormulaId) else ''
fNameMsg = '{} formula(e) with fileName {} with formulaId(s) {}'.format(str(len(existingFileNames)), fileName, str(existingIds)) if len(existingFileNames) else ''
self.cntlr.addToLog(_('DB has already {}{}{}, set "replaceExistingFormula" to True and enter a formulaId to update an existing formula by Id').format(
idMsg, ' and ' if idMsg and fNameMsg else '', fNameMsg), messageCode="RssDB.Info", file=self.conParams.get('database',''), level=logging.INFO)
return
if action == 'insert':
# get new id if id is not chosen
if not formulaId:
_ids = [x[0] for x in self.execute('SELECT max("formulaId") from "formulae"', fetch=True) if x[0]]
formulaId = max(_ids) + 1 if _ids else 1000
lb = ''
if formulaLinkBaseString:
lb = formulaLinkBaseString
elif os.path.isfile(fileName):
with open(fileName, 'r') as fp:
lb = fp.read().replace('\n', '')
if lb:
lb_xml = etree.fromstring(lb).getroottree()
lb_string = etree.tostring(lb_xml) # , pretty_print=True, encoding=lb_xml.docinfo.encoding if lb_xml.docinfo.encoding else None
formulaLinkBaseString = lb_string.decode(lb_xml.docinfo.encoding)
else:
raise Exception('No valid file path or formula linkbase string was provided')
formulaData = {
'formulaId': formulaId,
'fileName': fileName,
'description': description if description else os.path.basename(fileName),
'formulaLinkbase': formulaLinkBaseString,
'dateTimeAdded': datetime.now().replace(microsecond=0)
}
try:
self.insertUpdateRssDB(formulaData, 'formulae', action=action, updateCols=None, idCol='formulaId', commit=True, returnStat=False)
self.cntlr.addToLog(_('Formula id "{}" {}').format(formulaId, action + ('ed' if action=='insert' else 'd')), messageCode="RssDB.Info", file=self.conParams.get('database',''), level=logging.INFO)
except Exception as e:
if self.product == 'postgres':
pg8000.paramstyle = pgParamStyle
self.rollback()
raise e
if self.product == 'postgres':
pg8000.paramstyle = pgParamStyle
res = None
if returnData:
res = formulaData
return res
def removeFormulaFromDb(self, formulaIds):
try:
placeholders = ', '.join(['?'] * len(formulaIds))
qry = 'DELETE FROM "formulae" WHERE "formulaId" in ({})'.format(placeholders)
self.execute(qry, params=tuple(formulaIds), fetch=False, commit=True)
self.addToLog(_('Removed formula(e) with id(s) {}').format(str(formulaIds)), messageCode="RssDB.Info", file=self.conParams.get('database', ''), level=logging.INFO)
except Exception as e:
self.rollback()
self.addToLog(_('Error while removing formula(e) with id(s) {}:\n{}').format(str(formulaIds), str(e)), messageCode="RssDB.Error", file=self.conParams.get('database', ''), level=logging.ERROR)
return
def startDBReport(self, host='0.0.0.0', port=None, debug=False, asDaemon=True, fromDate=None, toDate=None, threaded=True):
return _startDBReport(self, host, port, debug, asDaemon, fromDate, toDate, threaded)
def checkConnection(self):
chk = False
try:
db = self.conParams['database']
if self.product == 'postgres':
chk = self.execute('SELECT current_database();', fetch=True)[0][0] == db
elif self.product == 'sqlite':
if db == ':memory:':
chk = True
else:
chk = os.path.basename(self.execute('PRAGMA database_list;', fetch=True)[0][2]) == os.path.basename(db)
except Exception as e:
pass
return chk
def getDbStats(self):
result = {'textResult': OrderedDict(), 'dictResult':OrderedDict()}
qry = '''select 'LastUpdate' as description, cast(max("lastUpdate") as text) as val from "lastUpdate"
union all
select 'LatestFiling' as description, cast(max("pubDate") as text) as val from "filingsInfo"
union all
select 'EarliestFiling' as description, cast(min("pubDate") as text) as val from "filingsInfo"
union all
select 'CountFilings' as description, cast(count("filingId") as text) as val from "filingsInfo" where "duplicate"=0
union all
select 'LatestFeed' as description, cast(max("feedId") as text) as val from "feedsInfo"
union all
select 'EarliestFeed' as description, cast(min("feedId") as text) as val from "feedsInfo"
union all
select 'CountFeeds' as description, cast(count("feedId") as text) as val from "feedsInfo"
union all
select 'CountFilers' as description, cast(count("cikNumber") as text) as val from "filersInfo"
union all
select 'CountFiles' as description, cast(count("fileId") as text) as val from "filesInfo"
'''
if self.checkConnection():
if self.verifyTables(createTables=False):
stats = self.execute(qry, fetch=True)
_result = {x[0]:x[1] for x in stats}
if _result:
dbSize = ''
if self.product == 'postgres':
try:
_relsSize = '''SELECT sum(pg_relation_size(quote_ident(schemaname) || '.' || quote_ident(tablename)))
FROM pg_tables
WHERE schemaname = \'{}\' '''
_dbSize = self.execute(_relsSize.format(self.conParams['schema']))[0][0]
dbSize = convert_size(_dbSize, 'GB')[2]
except Exception as e:
self.rollback()
elif self.product == 'sqlite':
try:
_dbfile = self.conParams['database']
if os.path.isfile(_dbfile):
_dbSize = os.path.getsize(_dbfile)
dbSize = convert_size(_dbSize, 'GB')[2]
except:
conn.rollback()
_result['DatabaseSize'] = dbSize
result['dictResult'] = _result
timeSinceLastUpdate = 'Never Updated'
if parser.parse(_result['LastUpdate']).year == 1970:
_result['LastUpdate'] = None
timeSinceLastUpdate = 'Never Updated'
else:
td = parser.parse(datetime.today().strftime("%Y-%m-%d %H:%M:%S")) - parser.parse(_result['LastUpdate'])
days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
timeSinceLastUpdate = '{} days, {} hours, {} minutes since last update'.format(days, hours, minutes)
result['textResult'] = OrderedDict([
('LastUpdate', str(_result['LastUpdate']) + ' - ('+timeSinceLastUpdate+')' if _result['LatestFiling'] else 'No Data'),
('CountFeeds', _result['CountFeeds']),
('LatestFeed', str(_result['LatestFeed'])[:4] + '-' + str(_result['LatestFeed'])[-2:] if _result['LatestFeed'] else 'No Data'),
('EarliestFeed', str(_result['EarliestFeed'])[:4] + '-' + str(_result['EarliestFeed'])[-2:] if _result['EarliestFeed'] else 'No Data'),
('CountFilings', _result['CountFilings']),
('LatestFiling', str(_result['LatestFiling']) if _result['LatestFiling'] else 'No Data'),
('EarliestFiling', str(_result['EarliestFiling']) if _result['EarliestFiling'] else 'No Data'),
('CountFiles', str(_result['CountFiles']) if _result['CountFiles'] else 'No Data'),
('CountFilers', _result['CountFilers']),
('DatabaseSize', _result['DatabaseSize'])
])
else:
result['textResult'] = {'missingTables': ', '.join(set(rssTables) - self.tablesInDB())}
else:
result['textResult'] = {'noConnection': 'Could not connect to database'}
return result
def getReportData(self, fromDate=None, toDate=None):
'''Get summaries used in db report'''
if not self.verifyTables(createTables=False):
return False
# validate Dates
for k,v in {'From': fromDate, 'To': toDate}.items():
if v:
try:
datetime.strptime(v, '%Y-%m-%d')
except:
self.cntlr.addToLog(_('{} Date is not in the correct fromat, date should be in the format yyyy-mm-dd').format(k),
messageCode="RssDB.Error", file=self.conParams.get('database', ''), level=logging.ERROR)
return
if (fromDate and toDate) and (datetime.strptime(toDate, '%Y-%m-%d') <= datetime.strptime(fromDate, '%Y-%m-%d')):
self.cntlr.addToLog(_('To Date must be later than From date'),
messageCode="RssDB.Error", file=self.conParams.get('database', ''), level=logging.ERROR)
return
dbStats = self.getDbStats()['dictResult']
if not fromDate and not toDate:
lastFiling = dbStats.get('LatestFiling', None)
if lastFiling:
lastFilingYear = parser.parse(lastFiling).date().year
fromDate = str(date(lastFilingYear-2, 1, 1))
qFromDate = 'and "filingDate">=\'{}\''.format(str(fromDate)) if fromDate else ''
qToDate = 'and "filingDate"<=\'{}\''.format(str(toDate)) if toDate else ''
# filings summary query
sql1 = '''
with x as (
select a."cikNumber", b."conformedName", a."feedId", a."formType", a."assignedSic", a."inlineXBRL", count(a."filingId") as "count"
from "filingsInfo" a
left join "filersInfo" b on a."cikNumber" = b."cikNumber"
where a."duplicate" = 0 {} {}
group by a."cikNumber", b."conformedName", a."feedId", a."formType", a."assignedSic", a."inlineXBRL" order by a."feedId" desc)
select x.*, c."feedMonth" from x left join "feedsInfo" c on x."feedId"=c."feedId"
'''.format(qFromDate, qToDate)
# filers' locations
sql2 = '''select a."cikNumber", a."conformedName", b.*
from "filersInfo" a left join "locations" b on lower(a."businessState") = lower(b."code")'''
q1 = self.execute(sql1, fetch=True, close=False)
cols1 = [x[0].decode() if isinstance(x[0], bytes) else x[0] for x in self.cursor.description]
filingsDataDict = [dict(zip(cols1, x)) for x in q1]
with open(os.path.join(pathToSQL,'mongodbIndustryClassification.json'), 'r') as industries:
industry = json.load(industries)
res_industry = dict()
for a in industry['industry']:
if a['industry_classification'] == 'SEC':
res_industry[str(a['industry_code'])] = {'division_name': a['ancestors'][0]['industry_description'] if a['ancestors'] else 0}
q2 = self.execute(sql2, fetch=True, close=False)
cols2 = [x[0].decode() if isinstance(x[0], bytes) else x[0] for x in self.cursor.description]
locationsDict = [dict(zip(cols2, x)) for x in q2]
return dbStats, filingsDataDict, res_industry, locationsDict
def showStatus(self, msg, clearAfter=2000, end='\n'):
if self.cntlr is not None:
if 'end' in self.cntlr.showStatus.__code__.co_varnames:
self.cntlr.showStatus(msg, clearAfter, end=end)
elif isinstance(self.cntlr, CntlrCmdLine):
print(msg, end=end)
else:
self.cntlr.showStatus(msg, clearAfter)
return
def addToLog(self, msg, **kwargs):
if self.cntlr is not None:
self.cntlr.addToLog(msg, **kwargs)