libbatch
index
/grande/definitivo/definitivo/Programacion/CVS/Package/AutoCodeGenerator/libbatch.py

# AutoCodeGenerator is a configuration generator tool which is able to generate 
# other programs that insert, delete, or update database records
#
# Copyright (C) 2004  Manel Cebolla Benedito

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#  
# You can contact me at: manelelena@manelelena.com

 
Modules
       
ConfigParser
inspect
os
standout
string
sys
time

 
Functions
       
st_cfg_delete_option(st_file, st_section, st_option)
Deletes a options in a ini file
Ex.
file.ini:
[flow]
up=1
-->
st_cfg_delete_option("/tmp/file.ini", "flow", "up")
st_cfg_delete_section(st_file, st_section)
Erase a section in a config ini file
Ex.
st_cfg_delete_section("/tmp/file.ini", "flow")
st_cfg_load(st_file)
Loads ini file and returns file contents in a dictionary
Ex.
file.ini:
[a]
b=1
c=2
st_cfg_load("/tmp/file.ini")
st_cfg_modify_option(st_file, st_section, st_option, st_value)
Modifies a option in a ini file. If option doenst exist it creates the option
Ex.
file.ini:
[flow]
a=1
b=2
st_cfg_modify_option("/tmp/file.ini", "flow", "a", "100")
st_color(text, fg, bg=None, raw=0)
Writes string with the desired color text and color backgroud.
Color is one of the defined literal: black red green brown blue purple
cyan lgray gray lred lgreen yellow lblue pink lcyan white lyellow.
This functions is used internally by st_log_message
Ex.
print st_color("hello", "white")
print st_color("hello","blue", gb="white")
st_data_backup_infile(st_cursor, st_table_list, st_indir, st_database='uoc')
Restore a backup of a table 
If you use MySQL backupfile should be in server filesystem
Ex.
st_data_backup_infile(colter, ["clientes", "proveedor"], "/tmp", st_database="bichejo")
st_data_backup_outfile(st_cursor, st_table_list, st_outdir, st_database='uoc')
Makes a backup copy of a list of tables/views 
If you use MySQL it only works if host is the same than the server
Ex.
st_data_backup_outfile(colter, ['clientes', 'proveedores'], "/tmp", st_database="bichejo")
st_data_bulk_infile(st_cursor, st_table, st_infile, st_location='LOCAL', st_extra_parameters='', st_database='uoc')
Loads a data file into a table of a database. If infile is in the host st_location should have "LOCAL"
In MySQL LOCAL mode, it only copies record that dont break a primary key, if some data  breaks key function doesnt fail
Ex. 
load data infile "/tmp/clientes.bcp" into table clientes
-->
st_data_bulk_infile(colter, "clientes", "/tmp/clientes.bcp", st_database="bichejo")
st_data_bulk_outfile(st_cursor, st_select, st_from_where, st_outfile, st_extra_parameters='', st_database='uoc')
Export a table/view (bulk copy).
If you use MySQL st_outfile will be placed at the server host filesystem
Before to copy file this functions tries to delete it, it host isnt server then file will not be deleted
 
Ex.
select field1, field2 into "/tmp/clientes.bcp" from clientes where a=1
-->
st_data_bulk_outfile(colter, "select field1, field2", "from clientes", "where a=1", st_database="bichejo")
st_exception_info()
Return name, args and traceback of the last exception, I use this function in my except: clauses before exit the program
Ex.
try:
        a=aaaaa
except:
        st_log_message(ST_ALERT, str(st_exception_info())
        st_log_message(ST_ERROR, "A problem has occurred here")
st_file_delete_directory(st_path)
Deletes directory, if it doesnt exists then shows a Warning message
Ex.
st_file_delete_directory("/tmp/a/b")
st_file_init_directory(st_path, st_delete_if_exists=True)
Executes:
st_file_delete_directory
st_file_verify_directory
st_file_verify_directory(st_path)
Verifies if a directory exists and if doesnt then creates it
Ex.
st_file_verify_directory("/tmp/a/b")
st_getframe(st_level=0)
Gets the frame of a function, if st_level=0 gets the actual function, st_frame=1 the caller of the actual function...
Ex.
def a():
        # The next line print the name of the frame
        print st_getframe().f_code.co_name
-->
a
........
def b():
        a()
-->
a
.......
def a():
        # Print the caller of the function a()
        print st_getframe(1).f_code.co_name
b()
-->
b
st_log_message(priority, text)
Used to show messages on screen or on file, can format messages for Warnings, Errors, [OK]...
and indicate that only should write on file or on screen...
 
Ex.
by default it writes all messages in logfile and screen (stdout)
 
st_log_message(ST_INFO, "hola info")            <date> INFO  hola info  
st_log_message(ST_WARN, "hola warn")            <date> WARN  hola warn                  (in red)
st_log_message(ST_ERROR, "hola error")          <date> ERROR hola error                 (in dark red and exits from de program with exit 1)
st_log_message(ST_ALERT, "hola alert")          <date> ALERT hola alert                 (in red)
st_log_message(ST_INFOK, "hola infok")          <date> INFO  hola infok         [OK]
st_log_message(ST_LOG, "hola log")              <date> LOG   hola log                   (only in logfile)
st_log_message(ST_LOGW, "hola logw")            <date> WARN  hola logwarn               (only in logfile and in red)
st_log_message(ST_ALERTOK, "hola alertok")      <date> ALERT hola alertok       [OK]
st_log_message_init(st_verbosity_screen=5, st_verbosity_logfile=5, st_logfile='')
Init of logging values.
st_vervosity_screen=6 or higher, doesnt show any message on stdout
st_vervosity_screen=5 (default value), will show on stdout messages with: ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK
st_verbosity_screen=4 (minimal debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_VERBOSE1
st_verbosity_screen=3 (medium debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_VERBOSE1 ST_VERBOSE2
st_verbosity_screen=2 (max debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_VERBOSE1 ST_VERBOSE2 ST_VERBOSE3
st_verbosity_screen=1 (panic debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_VERBOSE1 ST_VERBOSE2 ST_VERBOSE3 ST_VERBOSE4
 
st_vervosity_screen=6 or higher, doesnt show any message on logfile
st_vervosity_logfile=5 (default value), will show on logfile messages with: ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_LOG ST_LOGW
st_verbosity_logfile=4 (minimal debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_LOG ST_LOGW ST_VERBOSE1
st_verbosity_logfile=3 (medium debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_LOG ST_LOGW ST_VERBOSE1 ST_VERBOSE2
st_verbosity_logfile=2 (max debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_LOG ST_LOGW ST_VERBOSE1 ST_VERBOSE2 ST_VERBOSE3
st_verbosity_logfile=1 (panic debug mode): ST_INFO ST_WARN ST_ERROR ST_ALERT ST_INFOK ST_ALERTOK ST_LOG ST_LOGW ST_VERBOSE1 ST_VERBOSE2 ST_VERBOSE3 ST_VERBOSE4
 
ST_VERBOSE1        shows exception texts
ST_VERBOSE2        shows executed function name and parameters
st_misc_generate_zeroes(st_to)
Generates a string with zeroes, len os string is st_to
Ex.
print st_misc_generate_zeroes(10)
-->
0000000000
st_misc_get_next_temp_file_name(st_filename, st_max_extension)
Generates a file name, extension of filename will be a incremental number, it searches the last filename
in the filesystem and generates the next, st_max_extension is the len of the extension
Ex.
print st_misc_get_next_temp_file_name("examplefile", 3)
-->
examplefile.000
print st_misc_get_next_temp_file_name("examplefile", 3)
examplefile.001
...
st_misc_left_pad_with_zeroes(st_number, st_pad)
Generates a string adding zeroes on left to a number in order that new string will have a len of st_pad
Ex.
print st_misc_left_pad_with_zeroes(123, 10)
-->
0000000123
st_misc_progress_bar(ratio, length=60, col=1, cols=('lgreen', 'red', 'blue'), nocol='=.')
ratio - progress level, between 0 and 1
lenght - max len of bar 
col - if is greater than 0, bar is colored, if not uses nocol
nocol - character to use in case of no color
Ex.
progress(.1, length=100, col=0, nocol="+-")
progress(.2, length=100, col=0, nocol="+-")
progress(.3, length=100, col=0, nocol="+-")
progress(.4, length=100, col=0, nocol="+-")
progress(.5, length=100, col=0, nocol="+-")
progress(.6, length=100, col=0, nocol="+-")
progress(.7, length=100, col=0, nocol="+-")
progress(.8, length=100, col=0, nocol="+-")
progress(.9, length=100, col=0, nocol="+-")
st_misc_send_mail(st_fromaddr, st_toaddr, st_msg)
Sends a mail to st_toaddr from st_fromaddr with message st_msg
Ex.
st_misc_send_mail("masa@asas.es", "sada@asd.es", "asasasadwd asdasdadsadadasasd")
st_misc_valid_host_check(st_cursor)
Function for internal use, returns 1 if host is the same than server
Ex.
st_misc_valid_host_check(colter)
st_print_frame(st_frame)
st_process_fuser_count(st_filename)
This function only works in Linux Systems. fuser command. Return a count of processes that are accessinf to a file
Ex.
st_process_fuser_count("/tmp/a.txt")
st_process_get_pid()
This functions only works in Unix Systems. Returns the pid of the process
Ex.
process_pid=st_process_get_pid()
st_process_kill(st_pid, st_signal=9)
This functions only works in Unix Systems. Send st_signal to pid process
Ex.
st_process_kill(1212, st_signal=9)
st_process_wait()
This functions only works in Unix Systems. Waits until all children processes end
Ex.
st_process_wait()
st_process_waitpid(st_pid)
This functions only works in Unix Systems. Waits until pid ends, its only valid with children processes
Ex.
st_process_waitpid(1212)
st_sql_connect(st_enviroment_to_connect)
It connects to the enviroment passed via parameter. Enviroments are defined in libbatch.cfg
In the cfg file you should indicate user, pass, server, database program...
Ex.
colter=st_sql_connect("colter")
st_sql_count_table(st_enviroment_to_use, st_table, st_database='', st_schema='public')
Returns the count of record in st_table inside database st_database
PostgreSQL doesnt admit cross database queries so st_database to use is the default when connected
PostgreSQL has not yet implemented cross database from clauses, so st_database could not be used, you will allways use database specified in st_sql_connect
if none st_schema is specified this function uses public as default
Ex.
print st_sql_count_table(colter, "clientes", st_database="bichejo")
st_sql_create_index(st_enviroment_to_use, st_table, st_field_list, st_index_name, st_database='uoc')
Create index on table on database
PostgreSQL doesnt admit cross database queries so st_database to use is the default when connected
Ex.
st_sql_create_index("bichejo", "clientes", ["clientid", "clientservid"], "idx_clientes_clientesid", st_database="uoc")
st_sql_drop_index(st_enviroment_to_use, st_table, st_index, st_database='uoc')
Deletes refired index, if index doesnt exists writes a warning line at logfile but doesnt exit
PostgreSQL doesnt admit cross database queries so st_database to use is the default when connected
Ex.
st_sql_drop_index(colter, "clientes", "primario", st_database="bichejo")
st_sql_drop_procedure(st_enviroment_to_use, st_procedure, st_database='uoc')
Hasta la version 5 no hay procedures en MySql
Ex.
Postgres:
st_sql_drop_procedure("bichejo", "funcion(integer)")
st_sql_drop_table(st_enviroment_to_use, st_table, st_database='uoc', st_schema='public')
Deletes refired table, if table doesnt exists writes a warning line at logfile but doesnt exit
PostgreSQL doesnt admit cross database queries so st_database to use is the default when connected
PostgreSQL doesnt admit cross database queries so st_database to use is the default when connected
PostgreSQL has not yet implemented cross database from clauses, so st_database could not be used, you will allways use database specified in st_sql_connect
Ex.
st_sql_drop_table(colter, "clientes", st_database="bichejo")
st_sql_goto(st_enviroment_to_active)
Activates an enviroment, so functions call this enviroment until it is changed
st_sql_index_exists(st_enviroment_to_use, st_table, st_index_name, st_database='uoc')
Returns 1 if index exists and 0 if it doesnt
Ex.
print st_sql_index_exists(colter, "clientes", "PRIMARY", st_database="uoc")
print st_sql_index_exists(colter, "clientes", "PRIMARY", st_database="uoc")
st_sql_max_table(st_enviroment_to_use, st_table, st_field, st_database='', st_schema='public')
Returns the max value of st_field in st_table inside database st_database
PostgreSQL doesnt admit cross database queries so st_database to use is the default when connected
PostgreSQL has not yet implemented cross database from clauses, so st_database could not be used, you will allways use database specified in st_sql_connect
if none st_schema is specified this function uses public as default
Ex.
print st_sql_max_table(colter, "clientes", "edad", st_database="bichejo")
st_sql_min_table(st_enviroment_to_use, st_table, st_field, st_database='')
Returns the min value of st_field in st_table inside database st_database
PostgreSQL doesnt admit cross database queries so st_database to use is the default when connected
Ex.
print st_sql_min_table(colter, "clientes", "edad", st_database="bichejo")
st_sql_procedure_exists(st_enviroment_to_use, st_procedure, st_database='')
Returns 1 if procedure/function exists and 0 if it doesnt
In PostgreSQL functions can be overwritten so if one name is find it will return 1
Use of st_database not yet implemented
Ex.
print st_sql_procedure_exists(colter, "aaa" , st_database="uoc")
...
In PostgreSQL:
print st_sql_procedure_exists("bichejo", "a")
 
Until MySql 5.0 procedures/functions cant be defined so you cant use this function in previous versions of MySQL
st_sql_run(st_enviroment_to_use, st_query, st_critic=2, st_get_field_names=0, st_out=1)
Runs a SQL sentence against the connection (first parameters), to get a connection you should use st_sql_connect
Parameter st_get_field_names makes that this function returns two tuples: one with field names and other with the values list
st_out indicates if st_sql_run should return results or no (st_get_field_names makes st_out automatically for field names)
Ex.
st_sql_run(colter, "select * from clientes") 
st_sql_run(colter, "create index idx_1 on clientes(telef)", st_out=0)
st_sql_table_exists(st_enviroment_to_use, st_table, st_database='', st_schema='public')
Return 1 if table exists and 0 if it doesnt exists
PostgreSQL has not yet implemented cross database from clauses, so st_database could not be used, you will allways use database specified in st_sql_connect
if none st_schema is specified this function uses public as default
with postgres you can select a schema inside a database, so in Postgres you can use st_schema, in MySQL st_database=st_schema
Ex.
mysql (all these are the same, st_schema is not used when st_database is indicated)
print st_sql_table_exists(colter, "clientes", st_database="uoc") 
print st_sql_table_exists(colter, "clientes", st_schema="uoc") 
print st_sql_table_exists(colter, "clientes", st_schema="xxxxxxx", st_database="uoc") 
Postgres (st_database cant be used)
print st_sql_table_exists(colter, "clientes", st_schema="public")
print st_sql_table_exists(colter, "clientes", st_schema="pg_catalog")
st_sql_trigger_exists(st_enviroment_to_use, st_trigger, st_database='')
Returns 1 if trigger exists and 0 if it doesnt
PostgreSQL has not yet implemented cross database from clauses, so st_database could not be used, you will allways use database specified in st_sql_connect
if none st_schema is specified this function uses public as default
Only work with pg by now
Use of st_database not yet implemented
Ex.
print st_sql_trigger_exists(colter, "aaa" , st_database="uoc")

 
Data
        ST_ALERT = 3
ST_ALERTOK = 7
ST_ERROR = 2
ST_INFO = 0
ST_INFOK = 4
ST_LOG = 5
ST_LOGW = 6
ST_VERBOSE1 = 12
ST_VERBOSE2 = 11
ST_VERBOSE3 = 10
ST_VERBOSE4 = 9
ST_WARN = 1
colors = {'black': '30', 'blue': '34', 'brown': '33', 'cyan': '36', 'gray': '1;30', 'green': '32', 'lblue': '1;34', 'lcyan': '1;36', 'lgray': '37', 'lgreen': '1;32', ...}
enable_color = 1
libbatch_config_file = '/root/etc/libbatch.cfg'
log = <standout.StandOut instance>
st_enviroment = {'bichejo': {'db': 'uoc', 'host': 'bichejo', 'logdir': '/grande', 'passwd': '', 'server_type': 'pg', 'temp_db': 'uoc', 'user': 'mcebolla'}, 'colter': {'db': 'uoc', 'host': 'bichejo', 'logdir': '/grande', 'passwd': 'mcebolla', 'server_type': 'MySQLdb', 'temp_db': 'test', 'user': 'root'}, 'reporting': {'db': 'uoc', 'host': 'bichejo', 'logdir': './', 'passwd': 'mcebolla', 'server_type': 'MySQLdb', 'temp_db': 'test', 'user': 'root'}}