Last active
October 22, 2021 23:25
-
-
Save danizen/de40b4e6bfa713fc76d6fe2cfaa236cc to your computer and use it in GitHub Desktop.
SQL processing management command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from django.core.management.base import BaseCommand | |
from django.core.management import call_command | |
class Command(BaseCommand): | |
def handle(self, *args, **options): | |
# create a pipe and turn the output file descriptor into a Python IO object | |
infd, outfd = os.pipe() | |
outs = open(outfd, 'w') | |
# write a little SQL script that will run in the database shell | |
outs.write('set echo on;\n') | |
outs.write('sho user;\n') | |
outs.write('SELECT 2+1 FROM DUAL;\n') | |
outs.write("SELECT to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') Start_Time from dual;\n") | |
outs.write('sho user;\n') | |
outs.write('exit;\n') | |
# fork a sub-process | |
pid = os.fork() | |
if pid == 0: | |
# make stdin come from the pipe | |
os.dup2(infd, 0) | |
call_command('dbshell') | |
else: | |
print(f'Running dbhell in pid {pid}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment