66from shutil import make_archive
77from datetime import datetime
88from masonite .utils .location import base_path
9+ import subprocess
10+ import gzip
911
1012
1113class Backup :
@@ -23,7 +25,44 @@ def database(self):
2325 """
2426 Backup the database.
2527 """
26- pass
28+
29+ db_config = config ("database.databases" )
30+ default = db_config .get ("default" )
31+ connection = db_config .get (default )
32+ driver = connection .get ("driver" )
33+
34+ db_file_path = base_path ("{}.gz" .format ("database-" + str (datetime .timestamp (datetime .now ()))))
35+
36+ if driver == "sqlite" :
37+ pass
38+ elif driver == "mysql" :
39+ command_str = f"mysqldump -u { connection .get ('user' )} -p{ connection .get ('password' )} { connection .get ('database' )} "
40+
41+ elif driver == "postgres" :
42+ command_str = f"pg_dump -U{ connection .get ('user' )} -h{ connection .get ('host' )} -p{ connection .get ('port' )} -d{ connection .get ('database' )} "
43+
44+ elif driver == "mssql" :
45+ command_str = f"sqlcmd -S{ connection .get ('host' )} -U{ connection .get ('user' )} -P{ connection .get ('port' )} -d{ connection .get ('database' )} "
46+
47+ elif driver == "sqlserver" :
48+ command_str = f"sqlcmd -S{ connection .get ('host' )} -U{ connection .get ('user' )} -P{ connection .get ('port' )} -d{ connection .get ('database' )} "
49+
50+ elif driver == "oracle" :
51+ command_str = f"sqlplus -S{ connection .get ('user' )} /{ connection .get ('password' )} @{ connection .get ('host' )} :{ connection .get ('port' )} /{ connection .get ('database' )} "
52+
53+ if command_str :
54+ with gzip .open (db_file_path , "wb" ) as f :
55+ popen = subprocess .Popen (
56+ [command_str ],
57+ stdout = subprocess .PIPE ,
58+ shell = True ,
59+ universal_newlines = True ,
60+ )
61+ for stdout_line in iter (popen .stdout .readline , "" ):
62+ f .write (stdout_line .encode ('utf-8' ))
63+ popen .stdout .close ()
64+ popen .wait ()
65+ return db_file_path
2766
2867 def files (self ):
2968 """
@@ -45,9 +84,10 @@ def files(self):
4584 with tempfile .TemporaryDirectory () as tmp :
4685 shutil .copytree (
4786 self .backup_config .get ("source" ).get ("root" ),
48- pathlib .Path (tmp ).joinpath ("temporary_backup " ),
87+ pathlib .Path (tmp ).joinpath ("backup " ),
4988 ignore = shutil .ignore_patterns (* self .backup_config .get ("source" ).get ("excludes" )),
5089 )
5190
5291 with patch ("os.path.isfile" , side_effect = self .accept ):
5392 make_archive (path_to_archive , "zip" , tmp )
93+ return path_to_archive
0 commit comments