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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
| #!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import kinterbasdb
import kinterbasdb.typeconv_datetime_stdlib as tc_dt
import time, datetime, re, csv
"""
select distinct rdb$field_name from rdb$types
================================================
RDB$CHARACTER_SET_NAME
RDB$FIELD_SUB_TYPE
RDB$FIELD_TYPE
RDB$FUNCTION_TYPE
RDB$MECHANISM
RDB$OBJECT_TYPE
RDB$SYSTEM_FLAG
RDB$TRANSACTION_STATE
RDB$TRIGGER_TYPE
select * from rdb$types where rdb$field_name = 'RDB$SYSTEM_FLAG'
"""
# SQL: morceau de requête qui "donne" le type d'un paramètre.
# Pour fonctionner, il faut aussi adjoindre à la requête le
# morceau de requête: FBTableType
#
# "F" et l'alias de la table "RDB$Fields"
FBFieldType = """
CASE F.RDB$Field_Type
WHEN 7 THEN 'Smallint'
WHEN 8 THEN 'Integer'
WHEN 9 THEN 'Quad'
WHEN 10 THEN 'Float'
WHEN 11 THEN 'D_Float'
WHEN 12 THEN 'Date'
WHEN 13 THEN 'Time'
WHEN 16 THEN 'BigInt'
WHEN 17 THEN 'Boolean'
WHEN 27 THEN 'Double Precision'
WHEN 35 THEN 'TimeStamp'
WHEN 261 THEN 'Blob'
WHEN 701 THEN 'Decimal'
WHEN 702 THEN 'Numeric'
WHEN 14 THEN 'Char(' || F.RDB$Field_Length || ')'
|| CASE
WHEN( RT.RDB$Type_Name IS NOT NULL )THEN ' CHARACTER SET ' || RT.RDB$Type_Name
ELSE ''
END
WHEN 15 THEN 'Char2(' || F.RDB$Field_Length || ')'
|| CASE
WHEN( RT.RDB$Type_Name IS NOT NULL )THEN ' CHARACTER SET ' || RT.RDB$Type_Name
ELSE ''
END
WHEN 37 THEN 'VarChar(' || F.RDB$Field_Length || ')'
|| CASE
WHEN( RT.RDB$Type_Name IS NOT NULL )THEN ' CHARACTER SET ' || RT.RDB$Type_Name
ELSE ''
END
WHEN 38 THEN 'VarChar2(' || F.RDB$Field_Length || ')'
|| CASE
WHEN( RT.RDB$Type_Name IS NOT NULL )THEN ' CHARACTER SET ' || RT.RDB$Type_Name
ELSE ''
END
WHEN 40 THEN 'CString(' || F.RDB$Field_Length || ')'
|| CASE
WHEN( RT.RDB$Type_Name IS NOT NULL )THEN ' CHARACTER SET ' || RT.RDB$Type_Name
ELSE ''
END
WHEN 41 THEN 'CString2(' || F.RDB$Field_Length || ')'
|| CASE
WHEN( RT.RDB$Type_Name IS NOT NULL )THEN ' CHARACTER SET ' || RT.RDB$Type_Name
ELSE ''
END
END AS SType
"""
# Ce morceau de requête est utilisé conjointement avec le morceau de requête de ci-dessus.
# La liaison est faite par le champ "F.RDB$CHARACTER_SET_ID"
# "F.RDB$CHARACTER_SET_ID" existe dans la table RDB$FIELDS ou RDB$FUNCTION_ARGUMENTS
###############################################################################################
FBTableType = """
LEFT JOIN RDB$TYPES RT ON RT.RDB$FIELD_NAME = 'RDB$CHARACTER_SET_NAME'
AND RT.RDB$TYPE = F.RDB$CHARACTER_SET_ID
AND RT.RDB$DB_KEY = ( SELECT MIN( T.RDB$DB_KEY )
FROM RDB$TYPES T
WHERE T.RDB$Field_Name = RT.RDB$FIELD_NAME
AND T.RDB$Type = RT.RDB$Type
)
"""
##############################################################################
#
# Fonction indépendante qui permet "split" les données de connexion
#
##############################################################################
def SplitDSN( Connect ):
PosSep1 = Connect.find( '/' )
User = Connect[ : PosSep1 ]
PosSep2 = Connect.find( '@' )
Password = Connect[ PosSep1 + 1 : PosSep2 ]
DSN = Connect[ PosSep2 + 1 : ]
return( User, Password, DSN )
##############################################################################
#
# Fonction indépendante qui permet de convertir une chaîne "date & heure"
# en une valeur de type DateTime compatible avec les paramètres à
# transmettre à un insert par exemple.
#
##############################################################################
def StrToDateTime( Str, Format = '%Y-%m-%d %H:%M:%S' ):
"""Le format proposé décode une date et une heure au format iso:
Année-Mois-Jour heures:minutes:secondes
Les directives de formats dans ce cas sont:
%Y = année sur 4 chiffres
%m = mois sur 2 chiffres: 1..12
%d = jour sur 2 chiffres: 1..31
%H = heure sur 2 chiffres: 0..23
%M = minutes sur 2 chiffres: 0..59
%S = secondes sur 2 chiffres: 0..59
"""
try:
return datetime.datetime.fromtimestamp(
time.mktime(
time.strptime( Str, Format ) ) )
except:
return datetime.datetime.fromtimestamp(
time.mktime(
time.strptime( '1980.01.01 00:00:00', '%Y-%m-%d %H:%M:%S' ) ) )
##############################################################################
#
# TProc()
#
##############################################################################
class TProc:
###################################################################
#
def __init__( self, DB, ProcName ):
"""
Remplace "EXECUTE PROCEDURE( ? )"
Utilisation:
DB = jjDB.TDB( 'SYSDBA/masterkey@localhost:Employee' )
Proc = DB.NewProc( 'ADD_EMP_PROJ' )
Proc.Execute( ( EMP_NO, PROJ_ID ) )
Proc.Commit()
"""
self.DB = DB
self.ProcName = ProcName
self.Cursor = self.DB.DBConnect.cursor()
self.Output = None
self.Deadlock = 0
return
###################################################################
#
def Execute( self, Args = () ):
Count = 5
while Count:
try:
self.Cursor.callproc( self.ProcName, Args )
self.Output = self.Cursor.fetchone()
return self.Output
except kinterbasdb.ProgrammingError, Obj:
# Deadlock ou nombre d'essais dépassé?
if Obj[0] != -913 or Count <= 0:
raise Obj
# Laisse respirer le serveur
time.sleep( 0.8 )
self.Deadlock += 1
return self.Output
###################################################################
#
def Proc( self, ProcName ):
self.ProcName = ProcName
return
###################################################################
#
def Commit( self ):
Count = 5
while Count:
try:
self.DB.DBConnect.commit()
return
except kinterbasdb.ProgrammingError, Obj:
# Deadlock ou nombre d'essais dépassé?
if Obj[0] != -913 or Count <= 0:
raise Obj
# Laisse respirer le serveur
time.sleep( 0.8 )
self.Deadlock += 1
return
##############################################################################
#
# TQuery()
#
##############################################################################
class TQuery:
###################################################################
#
def __init__( self, DB, SQL = None, Args = None ):
"""
Constructeur de la classe Query.
CE: DB = Instance de la connexion à la base de données
-- La base de données doit-être déjà connectée.
SQL = Si précisé, ouvre de suite la requête, de la sorte,
il est possible en une opération de construire
l'instance du query, de la connecté et d'ouvrir
un ensemble de données.
CS: aucune
-- self.DB = instance de la connexion
self.RowCount = Après un Query( SELECT ) donne le nombre d'
enregistrements lu.
self.Row = Contenu d'un enregistrement
self.Active = False ==> pas de requête active
True ==> une requête est en cours.
self.Cursor = Instance du curseur fournisseur de données
self.Verbe = Contient le verbe SQL après exécution de la requête.
self.IsSelect = True si Verbe == 'SELECT'
self.Autocommit = True par défaut, mettre à False pour interdire le
commit automatique après une requête différente de SELECT
Méthodes disponibles:
=====================
Query( SQL ) ==> Permet de lancer une nouvelle requête. A noter
qu'il est possible de lancer une requête
à la création de cet objet.
Fetch() ==> Retourne un enregistrement.
FetchAll() ==> Retourne tous les enregistrements.
"""
self.DB = DB
self.RowCount = None
self.Row = None
self.Active = False
self.Eof = False
self.Verbe = None
self.IsSelect = None
self.AutoCommit = True
# Curseur pour les requêtes
self.Cursor = self.DB.DBConnect.cursor()
# Ouverture de la requête si la requête est précisée
# lors de l'appel du constructeur.
# Dans ce cas, il ne faut pas appeler la méthode: Query()
if SQL != None:
self.Query( SQL, Args )
return
###################################################################
#
def GetRowCount( self ):
return self.Cursor.rowcount
###################################################################
#
def Commit( self ):
self.DB.DBConnect.commit()
return
###################################################################
#
def Query( self, SQL = None, Args = None ):
"""
Open( SQL )
Ouverture d'une requête SELECT, UPDATE, INSERT, ...
"""
self.SQL = SQL
self.RowCount = -1
# Pas de requête, pas d'exécution!
if SQL == None or SQL == '':
return
# Lancement de la requête
if Args == None:
self.Cursor.execute( self.SQL )
else:
self.Cursor.execute( self.SQL, Args )
# Extraction du verbe SQL: SELECT, UPDATE, DROP, EXECUTE, ...
self.Verbe = re.findall( '\W*(\w+)', self.SQL )[0].upper()
# Commit la requête si le verbe n'est pas SELECT
if self.Verbe == 'SELECT':
self.Active = True
self.IsSelect = True
else:
self.IsSelect = False
self.Active = False
###################################################################
#
def Fetch( self ):
"""
Fetch()
Retourne un enregistrement (tableau) dont la structure
apparente est: <Nom du champ>=<Valeur>
Cette méthode est à utiliser Pex dans une boucle WHILE:
En sortie, le champ RowCount contient le numéro de l'enregistrement
courant (en commençant à 1) ainsi que la propriété: RowCount
"""
Row = self.Cursor.fetchonemap()
self.Row = {}
if Row:
if self.RowCount == -1:
self.RowCount = 1
else:
self.RowCount += 1
for Key, Value in Row.items():
self.Row[ Key ] = Value
self.Row[ 'RowCount' ] = self.RowCount
return True
# Signale qu'il n'existe plus aucun enregistrement de disponible
self.Eof = True
return False
###################################################################
#
def FetchStr( self,
RecordPatron = '%s\n',
FieldPatron = '%(F)s\t',
NewSpace = '',
NewLigne = '',
FieldPatron1Pair = '',
FieldPatron1Impair = '',
FieldPatron2Pair = '',
FieldPatron2Impair = ''
):
"""
BUT; Extraire un enregistrement de l'ensemble de données et
formate colonne par colonne avec le patron précisé
en paramètre.
"""
Row = self.Cursor.fetchonemap()
self.Row = ''
if Row:
if self.RowCount == -1:
self.RowCount = 1
else:
self.RowCount += 1
# Ligne impaire?
if self.RowCount % 2 == 1:
# Ligne impaire
if FieldPatron1Impair != '':
FieldPatronImpair = FieldPatron1Impair # Ligne impaire: colonne impaire
else:
FieldPatronImpair = FieldPatron # Ligne impaire, patron normal
if FieldPatron1Pair != '':
FieldPatronPair = FieldPatron1Pair # Ligne impaire: colonnepaire
else:
FieldPatronPair = FieldPatron # Ligne impaire, patron normal
else:
# Ligne paire
if FieldPatron2Impair != '':
FieldPatronImpair = FieldPatron2Impair # Ligne paire: colonne impaire
else:
FieldPatronImpair = FieldPatron # Ligne paire, patron normal
if FieldPatron2Pair != '':
FieldPatronPair = FieldPatron2Pair # Ligne paire: colonne paire
else:
FieldPatronPair = FieldPatron # Ligne paire, patron normal
FieldNum = 0
# Les espaces/retour ligne sont-ils remplacés par un autre caractère/chaîne?
if NewSpace == '' and NewLigne == '':
# Les espaces restent inchangés
for Key, Value in Row.items():
StrValue = { 'F': str( Value ) }
if FieldNum % 2 == 1:
self.Row += FieldPatronImpair % StrValue
else:
self.Row += FieldPatronPair % StrValue
FieldNum += 1
else:
# Les espaces sont remplacés par le(s) caractère(s) précisé par NewSpace
for Key, Value in Row.items():
StrValue = { 'F': str( Value ).replace( ' ', NewSpace ).replace( '\n', NewLigne ) }
if FieldNum % 2 == 1:
self.Row += FieldPatronImpair % StrValue
else:
self.Row += FieldPatronPair % StrValue
FieldNum += 1
self.Row = RecordPatron % self.Row
return True
# Signale qu'il n'existe plus aucun enregistrement de disponible
self.Eof = True
return False
###################################################################
#
def FetchAll( self ):
"""
FetchAll()
Retourne un enregistrement (tableau) dont la structure
apparente est: <Nom du champ>=<Valeur>
Cette méthode est à utiliser Pex dans une boucle FOR:
DB = TDB()
Query = DB.Query()
I = 0
for Row in Query.FetchAll():
I += 1
print 'Employe = %(First_Name)s' %Row
print 'Count = %d' %( I )
"""
return self.Cursor.itermap()
###################################################################
#
def FieldsNames( self ):
"""
Retourne une liste avec les noms des champs
"""
Result = []
for FieldDesc in self.Cursor.description:
Result.append( FieldDesc[ kinterbasdb.DESCRIPTION_NAME ] )
return Result
###################################################################
#
def FieldsDescript( self ):
"""
Retourne une liste avec les noms des champs, leurs types: "char, integer, ..."
leur longueur et la contrainte not null si présente ainsi que le nom
Les informations sont enregistrés dans des dictionnaires suivant le format
[ { FieldName, FieldType, FieldSize, FieldPrecision, FieldNull }, # 1er champ
{ FieldName, FieldType, FieldSize, FieldPrecision, FieldNull }, # 2ème champ
...
]
"""
Result = []
for FieldDesc in self.Cursor.description:
if FieldDesc[ kinterbasdb.DESCRIPTION_NULL_OK ]:
FieldNull = 'NULLABLE'
else:
FieldNull = 'NOT NULL'
Result.append( { 'FieldName' : FieldDesc[ kinterbasdb.DESCRIPTION_NAME ],
'FieldType' : FieldDesc[ kinterbasdb.DESCRIPTION_DATA_TYPE_LIB ],
'FieldSize' : str( FieldDesc[ kinterbasdb.DESCRIPTION_INTERNAL_SIZE ] ),
'FieldPrecision' : str( FieldDesc[ kinterbasdb.DESCRIPTION_PRECISION ] ),
'FieldNull' : FieldNull
} )
return Result
##############################################################################
#
# TDB() Connexion à la base de données
#
##############################################################################
class TDB:
###################################################################
#
def __init__( self, Connect = 'SYSDBA/masterkey@127.0.0.1:employee',
SGDB = 'firebird' ):
"""
TDB( Connect, SGDB )
Construction de l'instance et connexion à la base de données.
Exemple: DB = TDB( 'SYSDBA/masterkey@localhost:employee', 'firebird' )
ou DB = TDB( Connect = 'SYSDBA/masterkey@localhost:employee', SGDB = 'firebird' )
Méthodes disponibles:
=====================
Owners() ==> liste des noms des utilisateurs de la base de données
Objects() ==> liste des objets de la base de données, tables, triggers, ...
NewQuery() ==> Création d'une nouvelle instance de query. Il est possible
de transmettre en paramètre directement la requête SQL
"""
self.SGDB = SGDB
self.Connect = Connect
# Extraction des éléments de la connexion
( self.User, self.Password, self.DSN ) = SplitDSN( Connect )
if SGDB != 'firebird':
print 'Seul le sgdb "firebird" est disponible !'
raise
self.DBConnect = kinterbasdb.connect( dsn = self.DSN,
user = self.User,
password = self.Password
)
# Classement de l'énumération des objets dans la base
# Mettre à 0 pour ne pas afficher l'objet
self.ObjectsOrder = { 'TABLE' : 1,
'VIEW' : 2,
'CHECK' : 3,
'PROCEDURE' : 4,
'TRIGGER' : 5,
'GENERATOR' : 6,
'FUNCTION' : 7,
'EXCEPTION' : 8,
'TABLESYS' : 9
}
self.InternalQuery = None
# wrapper pour les types de données dates
self.DBConnect.set_type_trans_in({
'DATE': tc_dt.date_conv_in,
'TIME': tc_dt.time_conv_in,
'TIMESTAMP': tc_dt.timestamp_conv_in,
#'FIXED': tc_fp.fixed_conv_in_precise,
})
self.DBConnect.set_type_trans_out({
'DATE': tc_dt.date_conv_out,
'TIME': tc_dt.time_conv_out,
'TIMESTAMP': tc_dt.timestamp_conv_out,
#'FIXED': tc_fp.fixed_conv_out_precise,
})
###################################################################
#
def __del__( self ):
try:
self.Close()
except:
pass
return
###################################################################
#
def Close( self ):
self.DBConnect.close()
return
###################################################################
#
def InternalQueryOpen( self, SQL, Args = None ):
if self.InternalQuery == None:
self.InternalQuery = TQuery( self, SQL, Args )
else:
self.InternalQuery.Query( SQL )
return self.InternalQuery
###################################################################
#
def Commit( self ):
self.DBConnect.commit()
return
###################################################################
#
def NewProc( self, ProcName ):
"""Création d'une nouvelle instance de TProc()
"""
Proc = TProc( self, ProcName )
return Proc
###################################################################
#
def NewQuery( self, SQL = None, Args = None ):
"""Création d'une nouvelle instance de TQuery()
"""
Query = TQuery( self, SQL, Args )
return Query
###################################################################
#
def Owners( self ):
Result = []
self.InternalQueryOpen( 'SELECT DISTINCT RDB$OWNER_NAME AS NAME FROM RDB$RELATIONS' )
for Row in self.InternalQuery.FetchAll():
Result.append( Row[ 'NAME' ].rstrip() )
return Result
###################################################################
#
def Objects( self ):
"""Utilisez le dictionnaire ObjectsOrder pour définir l'ordre
d'affichage des objets.
Placez 0 dans la valeur, Pex: DB.ObjectsOrder[ 'TABLESYS' ] = 0
pour ne pas afficher l'objet.
"""
Result = []
Query = self.InternalQueryOpen( """
SELECT
CAST( %(TABLESYS)d AS INTEGER ) AS OBJ_ORDER,
CAST( 'TABLESYS' AS VARCHAR( 32) ) AS OBJ_TYPE,
CAST( RDB$RELATION_NAME AS VARCHAR( 32) ) AS OBJ_NAME,
CAST( '' AS VARCHAR(255) ) AS OBJ_INFO
FROM RDB$RELATIONS
WHERE RDB$SYSTEM_FLAG = 1
AND %(TABLESYS)d > 0
GROUP BY RDB$RELATION_NAME
UNION ALL
SELECT
CAST( %(TABLE)d AS INTEGER ),
CAST( 'TABLE' AS VARCHAR( 32) ),
CAST( RDB$RELATION_NAME AS VARCHAR( 32) ),
CAST( '' AS VARCHAR(255) )
FROM RDB$RELATIONS
WHERE RDB$SYSTEM_FLAG = 0
AND RDB$VIEW_SOURCE IS NULL
AND %(TABLE)d > 0
GROUP BY RDB$RELATION_NAME
UNION ALL
SELECT
CAST( %(VIEW)d AS INTEGER ),
CAST( 'VIEW' AS VARCHAR( 32) ),
CAST( RDB$RELATION_NAME AS VARCHAR( 32) ),
CAST( '' AS VARCHAR(255) )
FROM RDB$RELATIONS
WHERE RDB$SYSTEM_FLAG = 0
AND RDB$VIEW_SOURCE IS NOT NULL
AND %(VIEW)d > 0
GROUP BY RDB$RELATION_NAME
UNION ALL
SELECT
CAST( %(FUNCTION)d AS INTEGER ),
CAST( 'FUNCTION' AS VARCHAR( 32) ),
CAST( RDB$FUNCTION_NAME AS VARCHAR( 32) ),
CAST( RDB$MODULE_NAME AS VARCHAR(255) )
FROM RDB$FUNCTIONS
WHERE %(FUNCTION)d > 0
UNION ALL
SELECT
CAST( %(PROCEDURE)d AS INTEGER ),
CAST( 'PROCEDURE' AS VARCHAR( 32) ),
CAST( RDB$PROCEDURE_NAME AS VARCHAR( 32) ),
CAST( '' AS VARCHAR(255) )
FROM RDB$PROCEDURES
WHERE %(PROCEDURE)d > 0
UNION ALL
SELECT
CAST( %(EXCEPTION)d AS INTEGER ),
CAST( 'EXCEPTION' AS VARCHAR( 32) ),
CAST( RDB$EXCEPTION_NAME AS VARCHAR( 32) ),
CAST( RDB$MESSAGE AS VARCHAR(255) )
FROM RDB$EXCEPTIONS
WHERE %(EXCEPTION)d > 0
UNION ALL
SELECT
CAST( %(GENERATOR)d AS INTEGER ),
CAST( 'GENERATOR' AS VARCHAR( 32) ),
CAST( RDB$GENERATOR_NAME AS VARCHAR( 32) ),
CAST( '' AS VARCHAR(255) )
FROM RDB$GENERATORS G
WHERE RDB$SYSTEM_FLAG IS NULL
AND %(GENERATOR)d > 0
UNION ALL
SELECT
CAST( %(TRIGGER)d AS INTEGER ),
CAST( 'TRIGGER' AS VARCHAR( 32) ),
CAST( RDB$TRIGGER_NAME AS VARCHAR( 32) ),
CAST( CASE RDB$TRIGGER_TYPE
WHEN 1 THEN 'BEFORE_INSERT'
WHEN 2 THEN 'AFTER_INSERT '
WHEN 3 THEN 'BEFORE_UPDATE'
WHEN 4 THEN 'AFTER_INSERT '
WHEN 5 THEN 'BEFORE_DELETE'
WHEN 6 THEN 'AFTER_DELETE '
END
|| ' ' ||
CASE RDB$TRIGGER_INACTIVE
WHEN 0 THEN 'ACTIVE'
ELSE 'INACTIVE'
END
AS VARCHAR(255) )
FROM RDB$TRIGGERS
WHERE ( RDB$SYSTEM_FLAG = 0 ) OR ( RDB$SYSTEM_FLAG is NULL )
UNION ALL
SELECT
CAST( %(CHECK)d AS INTEGER ),
CAST( 'CHECK' AS VARCHAR( 32) ),
CAST( T.RDB$CONSTRAINT_NAME AS VARCHAR( 32) ),
CAST( '' AS VARCHAR(255) )
FROM RDB$CHECK_CONSTRAINTS T
JOIN RDB$TRIGGERS T2 ON T2.RDB$TRIGGER_NAME = T.RDB$TRIGGER_NAME
WHERE T2.RDB$SYSTEM_FLAG = 3
AND T.RDB$DB_KEY = ( SELECT MIN( T3.RDB$DB_KEY ) FROM RDB$CHECK_CONSTRAINTS T3
WHERE T3.RDB$CONSTRAINT_NAME = T.RDB$CONSTRAINT_NAME )
ORDER BY 1, 3
""" % self.ObjectsOrder )
for Row in self.InternalQuery.FetchAll():
Result.append( { 'OBJ_TYPE': Row[ 'OBJ_TYPE' ],
'OBJ_NAME': Row[ 'OBJ_NAME' ].strip(),
'OBJ_INFO': Row[ 'OBJ_INFO' ]
} )
return Result
###################################################################
#
def HeaderSource( self, Brackets = True ):
Results = []
NType = -1
MaxLen = 0
# Boucle balayant la liste des paramètres, d'abord les paramètres
# d'entrés, ensuite les paramètres de sortis.
for Row in self.InternalQuery.FetchAll():
NowNType = Row[ 'NTYPE' ]
NowSName = Row[ 'SNAME' ]
# Changement de type de paramètre, commence par NType = 0, dans ce cas,
# c'est les paramètres d'entrés et 1 si ce sont les paramètres de sorties
if NowNType != NType:
# Est-ce un paramètre d'entré?
if NowNType == 0:
if Brackets:
Results.append( '(' )
else:
# Retire la dernière virgule et ferme la liste
# des paramètres entrants
if NType == 0:
I = len( Results ) - 1
Results[I] = Results[I][:-1]
Results.append( ')' )
# Début de la liste des paramètres de sortie, ce qui précéde et soit
# le nom de la procédure/fonction, soit la parenthèse fermante
# de la liste des paramètres d'entrés.
Results.append( 'RETURNS(' )
# Type en cours pour la rupture de séquence
NType = Row[ 'NTYPE' ]
# Nom, type et longueur du paramètre
Results.append( NowSName + '§' + Row[ 'STYPE' ].rstrip() + ',' )
# Détermine la plus grande longueur des noms de paramètres
# pour une mise en forme plus bas
NowLen = len( NowSName.rstrip() )
if NowLen > MaxLen:
MaxLen = NowLen
# Fermeture de la liste des paramètres: entrés/sorties
if NType != -1:
# Retire la dernière virgule et ferme la liste
I = len( Results ) - 1
Results[I] = Results[I][:-1]
if Brackets:
Results.append( ')' )
# Formatage des espaces entres les noms des champs et des types
# Ceci permet de réduire le nombre d'espace qu'il y a entre le nom et son type
MaxLen += 1
for I in range( 0, len( Results ) ):
P = Results[I].find( '§' )
if P > 0: # en principe 31
Results[I] = ' ' + Results[I][:MaxLen] + Results[I][P + 1:]
elif P == 0:
Results[I] = ' ' + Results[I][P + 1:]
# Ajoute un retour ligne lorsque le header commence direct par "RETURNS"
if len( Results ) > 0:
if Results[0] == 'RETURNS(':
Results[0] = '\nRETURNS('
# Assemblage des morceaux pour former l'entête de la procédure/fonction
return '\n'.join( Results )
"""
SELECT P.RDB$PARAMETER_NAME PNAME,
P.RDB$PARAMETER_TYPE PTYPE,
F.RDB$FIELD_NAME AS DNAME,
F.RDB$FIELD_TYPE AS FTYPE,
F.RDB$FIELD_SUB_TYPE AS STYPE,
F.RDB$FIELD_LENGTH AS FLEN,
F.RDB$FIELD_PRECISION AS FPREC,
F.RDB$FIELD_SCALE AS FSCALE,
F.RDB$SEGMENT_LENGTH AS SEGLEN,
F.RDB$CHARACTER_SET_ID AS CHARID,
F.RDB$COLLATION_ID AS COLLID
FROM RDB$PROCEDURE_PARAMETERS P
INNER JOIN RDB$FIELDS F ON P.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME
WHERE P.RDB$PROCEDURE_NAME = 'ADD_EMP_PROJ'
"""
###################################################################
#
def SourceProcedure( self, ProcName, Action = 0 ):
"""
Action = 0 ==> produit une requête "alter"
1 ==> produit une requête "create"
2 ==> produit une requête "drop"
"""
ProcName = ProcName.upper()
if Action == 1:
StringCmd = 'CREATE PROCEDURE'
elif Action == 2:
return 'DROP PROCEDURE ' + ProcName
else:
StringCmd = 'ALTER PROCEDURE'
# Obtient les informations de l'entête de la procédure, c.a.d. les
# 2 listes de paramètres entrants et sortants
################################################################
Query = self.InternalQueryOpen( """
SELECT
P.RDB$Parameter_Type AS NType,
P.RDB$Parameter_Name AS SName,
""" + FBFieldType + """
FROM RDB$Procedure_Parameters P
JOIN RDB$Fields F ON F.RDB$Field_Name = P.RDB$Field_Source
""" + FBTableType + """
WHERE P.RDB$Procedure_Name = '""" + ProcName + """'
ORDER BY P.RDB$Parameter_Type, P.RDB$Parameter_Number
""" )
Result = self.HeaderSource()
# Récupération de la source
################################################################
Query = self.InternalQueryOpen( """
SELECT
RDB$Procedure_Source AS Source
FROM RDB$Procedures
WHERE RDB$Procedure_Name = '%s'
""" % ProcName )
Query.Fetch()
return StringCmd + ' ' + ProcName + Result + '\nAS' + Query.Row[ 'SOURCE' ]
###################################################################
#
def SourceFunction( self, FunctName ):
"""Retourne les sources de la fonction (UDF) précisée en paramètre
"""
FunctName = FunctName.upper()
# Obtient les informations de l'entête de la procédure, c.a.d. les
# 2 listes de paramètres entrants et sortants
################################################################
Query = self.InternalQueryOpen( """
SELECT
0 AS NType,
'' AS SName,
""" + FBFieldType + """
FROM RDB$Function_Arguments F
""" + FBTableType + """
WHERE F.RDB$Function_Name = '""" + FunctName + """' AND F.RDB$Argument_Position > 0
ORDER BY F.RDB$Argument_Position
""" )
Source = self.HeaderSource( False )
# Obtient les éléments généraux de la déclaration,
# ainsi que le l'unique paramètre de retour
######################################################
Query = self.InternalQueryOpen( """
SELECT
P.RDB$EntryPoint AS EntryPoint,
P.RDB$Module_Name AS ModuleName,
CASE WHEN( P.RDB$Return_Argument > 0 )THEN 'PARAMETER ' || P.RDB$Return_Argument
WHEN( F.RDB$Mechanism = -1 )THEN 'FREE_IT'
ELSE T.RDB$Type_Name
END AS ReturnArg,
""" + FBFieldType + """
FROM RDB$Functions P
LEFT JOIN RDB$Function_Arguments F ON F.RDB$Function_Name = P.RDB$Function_Name AND F.RDB$Argument_Position = 0
LEFT JOIN RDB$TYPES T ON T.RDB$Field_Name = 'RDB$MECHANISM' AND T.RDB$Type = F.RDB$Mechanism
""" + FBTableType + """
WHERE P.RDB$Function_Name = '""" + FunctName + "'" )
Query.Fetch()
Result = 'DECLARE EXTERNAL FUNCTION ' + FunctName + '\n' \
+ Source \
+ '\nRETURNS ' + Query.Row[ 'STYPE' ].rstrip() \
+ ' ' + Query.Row[ 'RETURNARG' ].rstrip() \
+ "\nENTRY_POINT '" + Query.Row[ 'ENTRYPOINT' ].rstrip() \
+ "' MODULE_NAME '" + Query.Row[ 'MODULENAME' ].rstrip() \
+ "'"
return Result
###################################################################
#
def SourceException( self, ExceptName ):
Query = self.InternalQueryOpen( """
SELECT
RDB$Exception_Name AS ExceptName,
RDB$Message AS INFO
FROM RDB$Exceptions
WHERE RDB$Exception_Name = '""" + ExceptName.upper() + "'" )
Query.Fetch()
Result = 'CREATE EXCEPTION ' + Query.Row[ 'EXCEPTNAME' ].rstrip() \
+ " '" + Query.Row[ 'INFO' ].rstrip() \
+ "'"
return Result
###################################################################
#
def SourceTrigger( self, TriggerName, Action = 0 ):
"""
Action = 0 ==> produit une requête "alter"
1 ==> produit une requête "create"
2 ==> produit une requête "drop"
3 ==> produit une requête "inactive"
4 ==> produit une requête "active"
"""
Query = self.InternalQueryOpen( """
SELECT
RDB$Trigger_Name AS Name,
RDB$Relation_Name AS RelationName,
CAST( RDB$Trigger_Sequence AS Varchar(3) ) AS Seq,
RDB$Trigger_Source AS Source,
CASE RDB$Trigger_Type
WHEN 1 THEN 'BEFORE INSERT'
WHEN 2 THEN 'AFTER INSERT'
WHEN 3 THEN 'BEFORE UPDATE'
WHEN 4 THEN 'AFTER UPDATE'
WHEN 5 THEN 'BEFORE DELETE'
WHEN 6 THEN 'AFTER DELETE'
END AS SType,
CASE RDB$Trigger_Inactive
WHEN 0 THEN 'ACTIVE'
ELSE 'INACTIVE'
END AS SActive
FROM RDB$Triggers
WHERE RDB$Trigger_Name = '""" + TriggerName.upper() + "'" )
Query.Fetch()
if Action == 1:
return 'CREATE TRIGGER ' + Query.Row[ 'NAME' ].rstrip() \
+ ' FOR ' + Query.Row[ 'RELATIONNAME' ].rstrip() \
+ '\n' + Query.Row[ 'SACTIVE' ].rstrip() \
+ ' ' + Query.Row[ 'STYPE' ] \
+ ' POSITION ' + Query.Row[ 'SEQ' ] \
+ '\n' + Query.Row[ 'SOURCE' ]
elif Action == 2:
return 'DROP TRIGGER ' + Query.Row[ 'NAME' ].rstrip()
elif Action == 3:
return 'ALTER TRIGGER ' + Query.Row[ 'NAME' ].rstrip() \
+ ' INACTIVE'
elif Action == 4:
return 'ALTER TRIGGER ' + Query.Row[ 'NAME' ].rstrip() \
+ ' ACTIVE'
else:
return 'ALTER TRIGGER ' + Query.Row[ 'NAME' ].rstrip() \
+ '\n' + Query.Row[ 'SOURCE' ]
###################################################################
#
def SourceCheck( self, TriggerName, Action = 0 ):
"""
Action = 0 ==> produit une requête "alter"
1 ==> produit une requête "create"
2 ==> produit une requête "drop"
"""
Query = self.InternalQueryOpen( """
SELECT
C.RDB$Constraint_Name AS Name,
T.RDB$Relation_Name AS RelationName,
T.RDB$Trigger_Source AS Source
FROM RDB$Triggers T
JOIN RDB$Check_Constraints C ON C.RDB$Trigger_Name = T.RDB$trigger_Name
WHERE RDB$Constraint_Name = '""" + TriggerName.upper() + """'
AND T.RDB$DB_KEY = ( SELECT MIN( T2.RDB$DB_KEY ) FROM RDB$Triggers T2
WHERE T2.RDB$DB_KEY = T.RDB$DB_KEY )
""" )
Query.Fetch()
if Action == 1:
return 'ALTER TABLE ' + Query.Row[ 'RELATIONNAME' ].rstrip() \
+ '\nADD CONSTRAINT ' + Query.Row[ 'NAME' ].rstrip() \
+ '\n' + Query.Row[ 'SOURCE' ]
elif Action == 2:
return 'ALTER TABLE ' + Query.Row[ 'RELATIONNAME' ].rstrip() \
+ '\nDROP CONSTRAINT ' + Query.Row[ 'NAME' ].rstrip()
else:
return 'Ne fonctionne pas dans le SQLShow!\n\n' \
+ 'SET TERM §;\n\n' \
+ 'ALTER TABLE ' + Query.Row[ 'RELATIONNAME' ].rstrip() \
+ '\nDROP CONSTRAINT ' + Query.Row[ 'NAME' ].rstrip() \
+ '\n§\n\n' \
+ 'ALTER TABLE ' + Query.Row[ 'RELATIONNAME' ].rstrip() \
+ '\nADD CONSTRAINT ' + Query.Row[ 'NAME' ].rstrip() \
+ '\n§\n\n' + Query.Row[ 'SOURCE' ] \
+ '\n§\n\nSET TERM ;§'
###################################################################
#
def SourceView( self, RelationName ):
Query = self.InternalQueryOpen( """
SELECT
RDB$Relation_Name AS Name,
RDB$View_Source AS Source
FROM RDB$Relations
WHERE RDB$Relation_Name = '""" + RelationName.upper() + """'
""" )
Query.Fetch()
return 'RECREATE VIEW ' + Query.Row[ 'NAME' ].rstrip() \
+ '\nAS\n' + Query.Row[ 'SOURCE' ]
###################################################################
#
def SourcePrimaryKey( self, RelationName ):
RelationName = RelationName.upper()
Query = self.InternalQueryOpen( """
SELECT
R.RDB$Relation_Name AS TableName,
I.RDB$Field_Name AS FieldName
FROM RDB$Index_Segments I
JOIN RDB$Relation_Constraints R ON I.RDB$Index_Name = R.RDB$Index_Name
WHERE R.RDB$Constraint_Name = '""" + RelationName + """'
AND R.RDB$Constraint_Type = 'PRIMARY KEY'
ORDER BY I.RDB$Field_Position
""" )
FieldNames = ''
TableName = ''
for Row in Query.FetchAll():
TableName = Row[ 'TABLENAME' ].rstrip()
FieldNames += ', ' + Row[ 'FIELDNAME' ].rstrip()
return 'ALTER TABLE ' + TableName \
+ '\nADD CONSTRAINT ' + RelationName \
+ ' PRIMARY KEY( ' + FieldNames[2:] + ' )'
###################################################################
#
def SourceIndex( self, RelationName, Action = 0 ):
"""
Action = 0 ==> Inutilisé, produit une requête "create"
1 ==> produit une requête "create"
2 ==> produit une requête "drop"
3 ==> produit une requête "inactive"
4 ==> produit une requête "active"
"""
RelationName = RelationName.upper()
Query = self.InternalQueryOpen( """
SELECT
I.RDB$Relation_Name AS TableName,
I.RDB$Unique_Flag AS UniqueFlag,
S.RDB$Field_Name AS FieldName
FROM RDB$Indices I
JOIN RDB$Index_Segments S ON S.RDB$Index_Name = I.RDB$Index_Name
WHERE I.RDB$Index_Name = '""" + RelationName + """'
ORDER BY S.RDB$Field_Position
""" )
FieldNames = ''
TableName = ''
UniqueFlag = 0
for Row in Query.FetchAll():
TableName = Row[ 'TABLENAME' ].rstrip()
UniqueFlag = Row[ 'UNIQUEFLAG' ]
FieldNames += ', ' + Row[ 'FIELDNAME' ].rstrip()
if UniqueFlag != 0:
UniqueFlag = 'UNIQUE '
else:
UniqueFlag = ''
if Action == 2:
return 'DROP INDEX ' + RelationName
elif Action == 3:
return 'ALTER INDEX ' + RelationName + ' INACTIVE'
elif Action == 4:
return 'ALTER INDEX ' + RelationName + ' ACTIVE'
else:
return 'CREATE ' + UniqueFlag \
+ 'INDEX ' + RelationName \
+ ' ON ' + TableName \
+ '( ' + FieldNames[2:] + ' )'
###################################################################
#
def SourceForeignKey( self, RelationName ):
RelationName = RelationName.upper()
Query = self.InternalQueryOpen( """
SELECT
AND R.RDB$Constraint_type = 'FOREIGN KEY'
a faire a faire a faire a faire a faire a faire a faire a faire a faire
""" )
return
###################################################################
#
def SourceTable( self, TableName,
Action = 0,
ProtoTableName = False
):
"""
Action = 0 ==> Inutilisé, produit une requête "create"
1 ==> produit une requête "create"
2 ==> produit une requête "drop"
3 ==> inutilisé
4 ==> inutilisé
5 ==> Produit une requête SELECT
6 ==> Produit une requête INSERT
"""
TableName = TableName.upper()
Query = self.InternalQueryOpen( """
SELECT
R.RDB$Field_Name AS FieldName,
""" + FBFieldType + """,
CASE WHEN ( R.RDB$NULL_FLAG IS NOT NULL AND R.RDB$NULL_FLAG = 1 ) OR
( F.RDB$NULL_FLAG IS NOT NULL AND F.RDB$NULL_FLAG = 1 )
THEN 'NOT NULL'
ELSE ''
END
AS NotNull
FROM RDB$Relation_Fields R
JOIN RDB$Fields F ON F.RDB$Field_Name = R.RDB$Field_Source
LEFT JOIN RDB$TYPES RT ON RT.RDB$FIELD_NAME = 'RDB$CHARACTER_SET_NAME'
AND RT.RDB$TYPE = F.RDB$CHARACTER_SET_ID
AND RT.RDB$DB_KEY = ( SELECT MIN( T.RDB$DB_KEY )
FROM RDB$TYPES T
WHERE T.RDB$Field_Name = RT.RDB$FIELD_NAME
AND T.RDB$Type = RT.RDB$Type
)
WHERE R.RDB$Relation_Name = '""" + TableName + """'
ORDER BY R.RDB$Field_Position
""" )
Fields = ''
if ProtoTableName:
TableName += '_BIS'
if Action == 2:
return 'DROP TABLE ' + TableName
elif Action in ( 5, 6 ):
for Row in Query.FetchAll():
Fields += Row[ 'FieldName' ].rstrip().capitalize() + ', '
Fields = Fields[:-2]
if Action == 5:
return 'SELECT ' + Fields + ' FROM ' + TableName + '\n'
else:
return 'INSERT INTO ' + TableName + '(' + Fields + ')\n'
else:
for Row in Query.FetchAll():
Fields += ' ' \
+ Row[ 'FieldName' ].rstrip() \
+ ' ' \
+ Row[ 'STYPE' ].rstrip() \
+ ' ' \
+ Row[ 'NOTNULL' ].rstrip() \
+ ',\n'
return 'CREATE TABLE ' + TableName + '\n(\n' + Fields[:-2] + '\n)\n'
###################################################################
#
def ExportCSV( self, SQL = 'select * from employee', FileName = 'foo.csv' ):
"""
Exportation des données dans un fichier au format CSV
"""
# Ouverture de l'ensemble de données et du fichier cible
Query = self.InternalQueryOpen( SQL );
Writer = csv.writer( open( FileName, 'w' ) )
# Transfert dans le fichier les noms des colonnes
Writer.writerow( Query.FieldsNames() )
# Transfert des données
for Row in Query.FetchAll():
Writer.writerow( Row.values() )
return
##############################################################################
#
# Lancement en tant que script: exemple
#
##############################################################################
#
# Fonctions des listes:
# append( 'new' ), insert( indice, 'new' ), extend( 'new', autre_liste )
# remove( 'new' ), index( 'new' )
if __name__ == "__main__":
import sys, datetime, time
# Création de la connexion avec la base de données
DB = TDB( 'SYSDBA/masterkey@127.0.0.1:employee' )
#print "="*60
#print DB.SourceFunction( 'ABREV2' )
#print "="*60
#print DB.SourceProcedure( 'ADD_EMP_PROJ' )
#print DB.SourceTrigger( 'SET_EMP_NO', False )
#print DB.SourceIndex( 'CUSTREGION' )
#print DB.SourcePrimaryKey( 'integ_2' )
#print DB.SourceForeignKey( 'integ_29' )
#DB.ExportCSV( 'select * from employee', 'foo' )
#print DB.SourceTable( 'employee', 6 )
#sys.exit()
print '===================================================='
print '=== 1) Exemple avec FetchAll:'
print '===================================================='
Q = DB.NewQuery( 'select * from employee' )
I = 0
for Row in Q.FetchAll():
I += 1
print 'Employe = %(First_Name)s' % Row
print 'Count = %d (%d)' %( I, Q.RowCount )
print '\n===================================================='
print '=== 2) Exemple avec Fetch:'
print '===================================================='
Q.Query( 'SELECT * FROM EMPLOYEE' )
I = 0
while Q.Fetch():
I += 1
print '(%(RowCount)d) Employe = %(FIRST_NAME)s %(LAST_NAME)s' % Q.Row
print 'Count = %d (%d)' %( I, Q.RowCount )
print '\n===================================================='
print '=== 3) Exemple avec 10 Fetch:'
print '===================================================='
Q.Query( 'SELECT * FROM EMPLOYEE' )
I = 0
while Q.Fetch():
I += 1
print '(%(RowCount)d) Employe = %(FIRST_NAME)s %(LAST_NAME)s' % Q.Row
if I >= 10:
break
print 'Count = %d (%d)' %( I, Q.RowCount )
print '\n===================================================='
print '=== 4) Noms des utilisateurs:'
print '=== avec la fonction DB.Owners()'
print '===================================================='
print DB.Owners()
print '\n===================================================='
print '=== 5) Noms des objets de la base: table, fonction:'
print '=== avec la fonction DB.Objects()'
print '===================================================='
DB.ObjectsOrder[ 'TABLESYS' ] = 0
ObjectsNames = DB.Objects()
for Row in ObjectsNames:
print '%(OBJ_TYPE)s: %(OBJ_NAME)s %(OBJ_INFO)s' % Row
print '\n===================================================='
print "=== 6) Création d'une table nommée A"
print '===================================================='
Q.Query( 'RECREATE TABLE A( A TimeStamp, B INTEGER )' )
DT = StrToDateTime( '31/12/2005 11:22:33', '%d/%m/%Y %H:%M:%S' )
VAL = int( 0.99 * 100 )
Q.Query( 'insert into a( a, b ) values( ?, ? )', (DT, VAL) )
DT = StrToDateTime( '2005-12-31 22:33:44' )
Q.Query( 'insert into a( a, b ) values( ?, ? )', (DT, 456) )
#DB.Commit() #facultatif, c'est déjà fait automatiquement
Q.Query( 'select * from a' )
while Q.FetchStr():
print Q.Row
print '\n===================================================='
print "=== 7) Récupération des sources d'une procédure"
print '===================================================='
print DB.SourceProcedure( 'ADD_EMP_PROJ' )
print '\n===================================================='
print "=== 8) Récupération des sources d'une fonction"
print '===================================================='
# n'existe pas dans la démo print DB.SourceFunction( 'FOO' )
print '\n===================================================='
print "=== 9) Récupération d'une exception"
print '===================================================='
print DB.SourceException( 'REASSIGN_SALES' )
print '\n===================================================='
print "=== 10) Récupération d'un trigger"
print '===================================================='
print DB.SourceTrigger( 'SET_EMP_NO', True ) |
Partager