1010CHUNKSIZE = 10 ** 6
1111CONNECTION_STRING = "sqlite:///{}" .format (DATABASE_NAME )
1212
13+ # Column dtypes for tables that trigger pandas mixed-type warnings when
14+ # loaded with the default low_memory chunked inference (see #1237).
15+ # Types mirror mimic-iii/buildmimic/postgres/postgres_create_tables.sql.
16+ TABLE_DTYPES = {
17+ "chartevents" : {
18+ "WARNING" : "Int64" ,
19+ "ERROR" : "Int64" ,
20+ "RESULTSTATUS" : "string" ,
21+ "STOPPED" : "string" ,
22+ },
23+ "datetimeevents" : {
24+ "WARNING" : "Int64" ,
25+ "ERROR" : "Int64" ,
26+ "RESULTSTATUS" : "string" ,
27+ "STOPPED" : "string" ,
28+ },
29+ "inputevents_cv" : {
30+ "ORIGINALRATE" : "float64" ,
31+ "ORIGINALRATEUOM" : "string" ,
32+ "ORIGINALSITE" : "string" ,
33+ },
34+ "noteevents" : {
35+ "CHARTTIME" : "string" ,
36+ "STORETIME" : "string" ,
37+ "ISERROR" : "string" ,
38+ },
39+ }
40+
1341
1442def _table_name_from_csv (filename : str ) -> str :
1543 """Derive SQL table name from a CSV path (literal suffix, not str.strip)."""
@@ -21,20 +49,39 @@ def _table_name_from_csv(filename: str) -> str:
2149 return name .lower ()
2250
2351
52+ def _read_csv (path , table , ** kwargs ):
53+ # low_memory=False avoids dtype re-inference across chunks; table-specific
54+ # dtypes pin the columns that otherwise flip between numeric/object.
55+ return pd .read_csv (
56+ path ,
57+ index_col = "ROW_ID" ,
58+ low_memory = False ,
59+ dtype = TABLE_DTYPES .get (table ),
60+ ** kwargs ,
61+ )
62+
63+
2464if os .path .exists (DATABASE_NAME ):
2565 msg = "File {} already exists." .format (DATABASE_NAME )
2666 print (msg )
2767 sys .exit ()
2868
69+ # Prefer .csv.gz when both exist for the same table; also load plain .csv
70+ # (import.sh already accepts both).
71+ files_by_table = {}
72+ for f in glob ("*.csv" ):
73+ files_by_table [_table_name_from_csv (f )] = f
2974for f in glob ("*.csv.gz" ):
75+ files_by_table [_table_name_from_csv (f )] = f
76+
77+ for table , f in sorted (files_by_table .items ()):
3078 print ("Starting processing {}" .format (f ))
31- table = _table_name_from_csv (f )
3279 if os .path .getsize (f ) < THRESHOLD_SIZE :
33- df = pd . read_csv (f , index_col = "ROW_ID" )
80+ df = _read_csv (f , table )
3481 df .to_sql (table , CONNECTION_STRING )
3582 else :
3683 # If the file is too large, let's do the work in chunks
37- for chunk in pd . read_csv (f , index_col = "ROW_ID" , chunksize = CHUNKSIZE ):
84+ for chunk in _read_csv (f , table , chunksize = CHUNKSIZE ):
3885 chunk .to_sql (table , CONNECTION_STRING , if_exists = "append" )
3986 print ("Finished processing {}" .format (f ))
4087
0 commit comments