[ Index ]
 

Code source de vtiger CRM 5.0.2

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/adodb/ -> adodb-datadict.inc.php (source)

   1  <?php
   2  
   3  /**
   4    V4.90 8 June 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
   5    Released under both BSD license and Lesser GPL library license. 
   6    Whenever there is any discrepancy between the two licenses, 
   7    the BSD license will take precedence.
   8      
   9    Set tabs to 4 for best viewing.
  10   
  11       DOCUMENTATION:
  12      
  13          See adodb/tests/test-datadict.php for docs and examples.
  14  */
  15  
  16  /*
  17      Test script for parser
  18  */
  19  
  20  // security - hide paths
  21  if (!defined('ADODB_DIR')) die();
  22  
  23  function Lens_ParseTest()
  24  {
  25  $str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0, zcol2\"afs ds";
  26  print "<p>$str</p>";
  27  $a= Lens_ParseArgs($str);
  28  print "<pre>";
  29  print_r($a);
  30  print "</pre>";
  31  }
  32  
  33  
  34  if (!function_exists('ctype_alnum')) {
  35  	function ctype_alnum($text) {
  36          return preg_match('/^[a-z0-9]*$/i', $text);
  37      }
  38  }
  39  
  40  //Lens_ParseTest();
  41  
  42  /**
  43      Parse arguments, treat "text" (text) and 'text' as quotation marks.
  44      To escape, use "" or '' or ))
  45      
  46      Will read in "abc def" sans quotes, as: abc def
  47      Same with 'abc def'.
  48      However if `abc def`, then will read in as `abc def`
  49      
  50      @param endstmtchar    Character that indicates end of statement
  51      @param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 
  52      @returns 2 dimensional array containing parsed tokens.
  53  */
  54  function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
  55  {
  56      $pos = 0;
  57      $intoken = false;
  58      $stmtno = 0;
  59      $endquote = false;
  60      $tokens = array();
  61      $tokens[$stmtno] = array();
  62      $max = strlen($args);
  63      $quoted = false;
  64      $tokarr = array();
  65      
  66      while ($pos < $max) {
  67          $ch = substr($args,$pos,1);
  68          switch($ch) {
  69          case ' ':
  70          case "\t":
  71          case "\n":
  72          case "\r":
  73              if (!$quoted) {
  74                  if ($intoken) {
  75                      $intoken = false;
  76                      $tokens[$stmtno][] = implode('',$tokarr);
  77                  }
  78                  break;
  79              }
  80              
  81              $tokarr[] = $ch;
  82              break;
  83          
  84          case '`':
  85              if ($intoken) $tokarr[] = $ch;
  86          case '(':
  87          case ')':    
  88          case '"':
  89          case "'":
  90              
  91              if ($intoken) {
  92                  if (empty($endquote)) {
  93                      $tokens[$stmtno][] = implode('',$tokarr);
  94                      if ($ch == '(') $endquote = ')';
  95                      else $endquote = $ch;
  96                      $quoted = true;
  97                      $intoken = true;
  98                      $tokarr = array();
  99                  } else if ($endquote == $ch) {
 100                      $ch2 = substr($args,$pos+1,1);
 101                      if ($ch2 == $endquote) {
 102                          $pos += 1;
 103                          $tokarr[] = $ch2;
 104                      } else {
 105                          $quoted = false;
 106                          $intoken = false;
 107                          $tokens[$stmtno][] = implode('',$tokarr);
 108                          $endquote = '';
 109                      }
 110                  } else
 111                      $tokarr[] = $ch;
 112                      
 113              }else {
 114              
 115                  if ($ch == '(') $endquote = ')';
 116                  else $endquote = $ch;
 117                  $quoted = true;
 118                  $intoken = true;
 119                  $tokarr = array();
 120                  if ($ch == '`') $tokarr[] = '`';
 121              }
 122              break;
 123              
 124          default:
 125              
 126              if (!$intoken) {
 127                  if ($ch == $endstmtchar) {
 128                      $stmtno += 1;
 129                      $tokens[$stmtno] = array();
 130                      break;
 131                  }
 132              
 133                  $intoken = true;
 134                  $quoted = false;
 135                  $endquote = false;
 136                  $tokarr = array();
 137      
 138              }
 139              
 140              if ($quoted) $tokarr[] = $ch;
 141              else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
 142              else {
 143                  if ($ch == $endstmtchar) {            
 144                      $tokens[$stmtno][] = implode('',$tokarr);
 145                      $stmtno += 1;
 146                      $tokens[$stmtno] = array();
 147                      $intoken = false;
 148                      $tokarr = array();
 149                      break;
 150                  }
 151                  $tokens[$stmtno][] = implode('',$tokarr);
 152                  $tokens[$stmtno][] = $ch;
 153                  $intoken = false;
 154              }
 155          }
 156          $pos += 1;
 157      }
 158      if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
 159      
 160      return $tokens;
 161  }
 162  
 163  
 164  class ADODB_DataDict {
 165      var $connection;
 166      var $debug = false;
 167      var $dropTable = 'DROP TABLE %s';
 168      var $renameTable = 'RENAME TABLE %s TO %s'; 
 169      var $dropIndex = 'DROP INDEX %s';
 170      var $addCol = ' ADD';
 171      var $alterCol = ' ALTER COLUMN';
 172      var $dropCol = ' DROP COLUMN';
 173      var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s';    // table, old-column, new-column, column-definitions (not used by default)
 174      var $nameRegex = '\w';
 175      var $nameRegexBrackets = 'a-zA-Z0-9_\(\)';
 176      var $schema = false;
 177      var $serverInfo = array();
 178      var $autoIncrement = false;
 179      var $dataProvider;
 180      var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
 181      var $blobSize = 100;     /// any varchar/char field this size or greater is treated as a blob
 182                              /// in other words, we use a text area for editting.
 183      
 184  	function GetCommentSQL($table,$col)
 185      {
 186          return false;
 187      }
 188      
 189  	function SetCommentSQL($table,$col,$cmt)
 190      {
 191          return false;
 192      }
 193      
 194  	function MetaTables()
 195      {
 196          if (!$this->connection->IsConnected()) return array();
 197          return $this->connection->MetaTables();
 198      }
 199      
 200  	function MetaColumns($tab, $upper=true, $schema=false)
 201      {
 202          if (!$this->connection->IsConnected()) return array();
 203          return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
 204      }
 205      
 206  	function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
 207      {
 208          if (!$this->connection->IsConnected()) return array();
 209          return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
 210      }
 211      
 212  	function MetaIndexes($table, $primary = false, $owner = false)
 213      {
 214          if (!$this->connection->IsConnected()) return array();
 215          return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
 216      }
 217      
 218  	function MetaType($t,$len=-1,$fieldobj=false)
 219      {
 220          return ADORecordSet::MetaType($t,$len,$fieldobj);
 221      }
 222      
 223  	function NameQuote($name = NULL,$allowBrackets=false)
 224      {
 225          if (!is_string($name)) {
 226              return FALSE;
 227          }
 228          
 229          $name = trim($name);
 230          
 231          if ( !is_object($this->connection) ) {
 232              return $name;
 233          }
 234          
 235          $quote = $this->connection->nameQuote;
 236          
 237          // if name is of the form `name`, quote it
 238          if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
 239              return $quote . $matches[1] . $quote;
 240          }
 241          
 242          // if name contains special characters, quote it
 243          $regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
 244          
 245          if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
 246              return $quote . $name . $quote;
 247          }
 248          
 249          return $name;
 250      }
 251      
 252  	function TableName($name)
 253      {
 254          if ( $this->schema ) {
 255              return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
 256          }
 257          return $this->NameQuote($name);
 258      }
 259      
 260      // Executes the sql array returned by GetTableSQL and GetIndexSQL
 261  	function ExecuteSQLArray($sql, $continueOnError = true)
 262      {
 263          global $log;
 264          $rez = 2;
 265          $conn = &$this->connection;
 266          $saved = $conn->debug;
 267          foreach($sql as $line) {
 268              
 269              if ($this->debug) $conn->debug = true;
 270              $log->debug($line);
 271              $ok = $conn->Execute($line);
 272              $conn->debug = $saved;
 273              if (!$ok) {
 274                  $log->fatal("Table Creation Error: Query Failed");
 275                  $log->fatal(" ");
 276                  if ($this->debug)
 277                         {
 278                      $log->fatal("InstallError: ".$conn->ErrorMsg());
 279                      ADOConnection::outp($conn->ErrorMsg());
 280                  }        
 281                  if (!$continueOnError) return 0;
 282                  $rez = 1;
 283              }
 284          }
 285          return $rez;
 286      }
 287      
 288      /*
 289           Returns the actual type given a character code.
 290          
 291          C:  varchar
 292          X:  CLOB (character large object) or largest varchar size if CLOB is not supported
 293          C2: Multibyte varchar
 294          X2: Multibyte CLOB
 295          
 296          B:  BLOB (binary large object)
 297          
 298          D:  Date
 299          T:  Date-time 
 300          L:  Integer field suitable for storing booleans (0 or 1)
 301          I:  Integer
 302          F:  Floating point number
 303          N:  Numeric or decimal number
 304      */
 305      
 306  	function ActualType($meta)
 307      {
 308          return $meta;
 309      }
 310      
 311  	function CreateDatabase($dbname,$options=false)
 312      {
 313          $options = $this->_Options($options);
 314          $sql = array();
 315          
 316          $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
 317          if (isset($options[$this->upperName]))
 318              $s .= ' '.$options[$this->upperName];
 319          
 320          $sql[] = $s;
 321          return $sql;
 322      }
 323      
 324      /*
 325       Generates the SQL to create index. Returns an array of sql strings.
 326      */
 327  	function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
 328      {
 329          if (!is_array($flds)) {
 330              $flds = explode(',',$flds);
 331          }
 332          
 333          foreach($flds as $key => $fld) {
 334              # some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
 335              $flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
 336          }
 337          
 338          return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
 339      }
 340      
 341  	function DropIndexSQL ($idxname, $tabname = NULL)
 342      {
 343          return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
 344      }
 345      
 346  	function SetSchema($schema)
 347      {
 348          $this->schema = $schema;
 349      }
 350      
 351  	function AddColumnSQL($tabname, $flds)
 352      {
 353          $tabname = $this->TableName ($tabname);
 354          $sql = array();
 355          list($lines,$pkey) = $this->_GenFields($flds);
 356          $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
 357          foreach($lines as $v) {
 358              $sql[] = $alter . $v;
 359          }
 360          return $sql;
 361      }
 362      
 363      /**
 364       * Change the definition of one column
 365       *
 366       * As some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
 367       * to allow, recreating the table and copying the content over to the new table
 368       * @param string $tabname table-name
 369       * @param string $flds column-name and type for the changed column
 370       * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
 371       * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
 372       * @return array with SQL strings
 373       */
 374  	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
 375      {
 376          $tabname = $this->TableName ($tabname);
 377          $sql = array();
 378          list($lines,$pkey) = $this->_GenFields($flds);
 379          $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
 380          foreach($lines as $v) {
 381              $sql[] = $alter . $v;
 382          }
 383          return $sql;
 384      }
 385      
 386      /**
 387       * Rename one column
 388       *
 389       * Some DBM's can only do this together with changeing the type of the column (even if that stays the same, eg. mysql)
 390       * @param string $tabname table-name
 391       * @param string $oldcolumn column-name to be renamed
 392       * @param string $newcolumn new column-name
 393       * @param string $flds='' complete column-defintion-string like for AddColumnSQL, only used by mysql atm., default=''
 394       * @return array with SQL strings
 395       */
 396  	function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
 397      {
 398          $tabname = $this->TableName ($tabname);
 399          if ($flds) {
 400              list($lines,$pkey) = $this->_GenFields($flds);
 401              list(,$first) = each($lines);
 402              list(,$column_def) = split("[\t ]+",$first,2);
 403          }
 404          return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
 405      }
 406          
 407      /**
 408       * Drop one column
 409       *
 410       * Some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
 411       * to allow, recreating the table and copying the content over to the new table
 412       * @param string $tabname table-name
 413       * @param string $flds column-name and type for the changed column
 414       * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
 415       * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
 416       * @return array with SQL strings
 417       */
 418  	function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
 419      {
 420          $tabname = $this->TableName ($tabname);
 421          if (!is_array($flds)) $flds = explode(',',$flds);
 422          $sql = array();
 423          $alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
 424          foreach($flds as $v) {
 425              $sql[] = $alter . $this->NameQuote($v);
 426          }
 427          return $sql;
 428      }
 429      
 430  	function DropTableSQL($tabname)
 431      {
 432          return array (sprintf($this->dropTable, $this->TableName($tabname)));
 433      }
 434      
 435  	function RenameTableSQL($tabname,$newname)
 436      {
 437          return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
 438      }    
 439      
 440      /*
 441       Generate the SQL to create table. Returns an array of sql strings.
 442      */
 443  	function CreateTableSQL($tabname, $flds, $tableoptions=false)
 444      {
 445          if (!$tableoptions) $tableoptions = array();
 446          
 447          list($lines,$pkey) = $this->_GenFields($flds, true);
 448          
 449          $taboptions = $this->_Options($tableoptions);
 450          $tabname = $this->TableName ($tabname);
 451          $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
 452          
 453          $tsql = $this->_Triggers($tabname,$taboptions);
 454          foreach($tsql as $s) $sql[] = $s;
 455          
 456          return $sql;
 457      }
 458      
 459  	function _GenFields($flds,$widespacing=false)
 460      {
 461          if (is_string($flds)) {
 462              $padding = '     ';
 463              $txt = $flds.$padding;
 464              $flds = array();
 465              $flds0 = Lens_ParseArgs($txt,',');
 466              $hasparam = false;
 467              foreach($flds0 as $f0) {
 468                  $f1 = array();
 469                  foreach($f0 as $token) {
 470                      switch (strtoupper($token)) {
 471                      case 'CONSTRAINT':
 472                      case 'DEFAULT': 
 473                          $hasparam = $token;
 474                          break;
 475                      default:
 476                          if ($hasparam) $f1[$hasparam] = $token;
 477                          else $f1[] = $token;
 478                          $hasparam = false;
 479                          break;
 480                      }
 481                  }
 482                  $flds[] = $f1;
 483                  
 484              }
 485          }
 486          $this->autoIncrement = false;
 487          $lines = array();
 488          $pkey = array();
 489          foreach($flds as $fld) {
 490              $fld = _array_change_key_case($fld);
 491          
 492              $fname = false;
 493              $fdefault = false;
 494              $fautoinc = false;
 495              $ftype = false;
 496              $fsize = false;
 497              $fprec = false;
 498              $fprimary = false;
 499              $fnoquote = false;
 500              $fdefts = false;
 501              $fdefdate = false;
 502              $fconstraint = false;
 503              $fnotnull = false;
 504              $funsigned = false;
 505              
 506              //-----------------
 507              // Parse attributes
 508              foreach($fld as $attr => $v) {
 509                  if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
 510                  else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
 511                  
 512                  switch($attr) {
 513                  case '0':
 514                  case 'NAME':     $fname = $v; break;
 515                  case '1':
 516                  case 'TYPE':     $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
 517                  
 518                  case 'SIZE':     
 519                                  $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
 520                                  if ($dotat === false) $fsize = $v;
 521                                  else {
 522                                      $fsize = substr($v,0,$dotat);
 523                                      $fprec = substr($v,$dotat+1);
 524                                  }
 525                                  break;
 526                  case 'UNSIGNED': $funsigned = true; break;
 527                  case 'AUTOINCREMENT':
 528                  case 'AUTO':    $fautoinc = true; $fnotnull = true; break;
 529                  case 'KEY':
 530                  case 'PRIMARY':    $fprimary = $v; $fnotnull = true; break;
 531                  case 'DEF':
 532                  case 'DEFAULT': $fdefault = $v; break;
 533                  case 'NOTNULL': $fnotnull = $v; break;
 534                  case 'NOQUOTE': $fnoquote = $v; break;
 535                  case 'DEFDATE': $fdefdate = $v; break;
 536                  case 'DEFTIMESTAMP': $fdefts = $v; break;
 537                  case 'CONSTRAINT': $fconstraint = $v; break;
 538                  } //switch
 539              } // foreach $fld
 540              
 541              //--------------------
 542              // VALIDATE FIELD INFO
 543              if (!strlen($fname)) {
 544                  if ($this->debug) ADOConnection::outp("Undefined NAME");
 545                  return false;
 546              }
 547              
 548              $fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
 549              $fname = $this->NameQuote($fname);
 550              
 551              if (!strlen($ftype)) {
 552                  if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
 553                  return false;
 554              } else {
 555                  $ftype = strtoupper($ftype);
 556              }
 557              
 558              $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
 559              
 560              if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
 561              
 562              if ($fprimary) $pkey[] = $fname;
 563              
 564              // some databases do not allow blobs to have defaults
 565              if ($ty == 'X') $fdefault = false;
 566              
 567              //--------------------
 568              // CONSTRUCT FIELD SQL
 569              if ($fdefts) {
 570                  if (substr($this->connection->databaseType,0,5) == 'mysql') {
 571                      $ftype = 'TIMESTAMP';
 572                  } else {
 573                      $fdefault = $this->connection->sysTimeStamp;
 574                  }
 575              } else if ($fdefdate) {
 576                  if (substr($this->connection->databaseType,0,5) == 'mysql') {
 577                      $ftype = 'TIMESTAMP';
 578                  } else {
 579                      $fdefault = $this->connection->sysDate;
 580                  }
 581              } else if ($fdefault !== false && !$fnoquote)
 582                  if ($ty == 'C' or $ty == 'X' or 
 583                      ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
 584                      if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') 
 585                          $fdefault = trim($fdefault);
 586                      else if (strtolower($fdefault) != 'null')
 587                          $fdefault = $this->connection->qstr($fdefault);
 588              $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
 589              
 590              if ($widespacing) $fname = str_pad($fname,24);
 591              $lines[$fid] = $fname.' '.$ftype.$suffix;
 592              
 593              if ($fautoinc) $this->autoIncrement = true;
 594          } // foreach $flds
 595          
 596          return array($lines,$pkey);
 597      }
 598      /*
 599           GENERATE THE SIZE PART OF THE DATATYPE
 600              $ftype is the actual type
 601              $ty is the type defined originally in the DDL
 602      */
 603  	function _GetSize($ftype, $ty, $fsize, $fprec)
 604      {
 605          if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
 606              $ftype .= "(".$fsize;
 607              if (strlen($fprec)) $ftype .= ",".$fprec;
 608              $ftype .= ')';
 609          }
 610          return $ftype;
 611      }
 612      
 613      
 614      // return string must begin with space
 615  	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
 616      {    
 617          $suffix = '';
 618          if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
 619          if ($fnotnull) $suffix .= ' NOT NULL';
 620          if ($fconstraint) $suffix .= ' '.$fconstraint;
 621          return $suffix;
 622      }
 623      
 624  	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
 625      {
 626          $sql = array();
 627          
 628          if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
 629              $sql[] = sprintf ($this->dropIndex, $idxname);
 630              if ( isset($idxoptions['DROP']) )
 631                  return $sql;
 632          }
 633          
 634          if ( empty ($flds) ) {
 635              return $sql;
 636          }
 637          
 638          $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
 639      
 640          $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
 641          
 642          if ( isset($idxoptions[$this->upperName]) )
 643              $s .= $idxoptions[$this->upperName];
 644          
 645          if ( is_array($flds) )
 646              $flds = implode(', ',$flds);
 647          $s .= '(' . $flds . ')';
 648          $sql[] = $s;
 649          
 650          return $sql;
 651      }
 652      
 653  	function _DropAutoIncrement($tabname)
 654      {
 655          return false;
 656      }
 657      
 658  	function _TableSQL($tabname,$lines,$pkey,$tableoptions)
 659      {
 660          $sql = array();
 661          
 662          if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
 663              $sql[] = sprintf($this->dropTable,$tabname);
 664              if ($this->autoIncrement) {
 665                  $sInc = $this->_DropAutoIncrement($tabname);
 666                  if ($sInc) $sql[] = $sInc;
 667              }
 668              if ( isset ($tableoptions['DROP']) ) {
 669                  return $sql;
 670              }
 671          }
 672          $s = "CREATE TABLE $tabname (\n";
 673          $s .= implode(",\n", $lines);
 674          if (sizeof($pkey)>0) {
 675              $s .= ",\n                 PRIMARY KEY (";
 676              $s .= implode(", ",$pkey).")";
 677          }
 678          if (isset($tableoptions['CONSTRAINTS'])) 
 679              $s .= "\n".$tableoptions['CONSTRAINTS'];
 680          
 681          if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
 682              $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
 683          
 684          $s .= "\n)";
 685          if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
 686          $sql[] = $s;
 687          
 688          return $sql;
 689      }
 690      
 691      /*
 692          GENERATE TRIGGERS IF NEEDED
 693          used when table has auto-incrementing field that is emulated using triggers
 694      */
 695  	function _Triggers($tabname,$taboptions)
 696      {
 697          return array();
 698      }
 699      
 700      /*
 701          Sanitize options, so that array elements with no keys are promoted to keys
 702      */
 703  	function _Options($opts)
 704      {
 705          if (!is_array($opts)) return array();
 706          $newopts = array();
 707          foreach($opts as $k => $v) {
 708              if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
 709              else $newopts[strtoupper($k)] = $v;
 710          }
 711          return $newopts;
 712      }
 713      
 714      /*
 715      "Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
 716      
 717      This function changes/adds new fields to your table. You don't
 718      have to know if the col is new or not. It will check on its own.
 719      */
 720  	function ChangeTableSQL($tablename, $flds, $tableoptions = false, $forceAlter = false) // GS Fix for constraint impl - forceAlter
 721      {
 722      global $ADODB_FETCH_MODE;
 723      
 724          $save = $ADODB_FETCH_MODE;
 725          $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
 726          if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
 727          
 728          // check table exists
 729          $save_handler = $this->connection->raiseErrorFn;
 730          $this->connection->raiseErrorFn = '';
 731          $cols = $this->MetaColumns($tablename);
 732          $this->connection->raiseErrorFn = $save_handler;
 733          
 734          if (isset($savem)) $this->connection->SetFetchMode($savem);
 735          $ADODB_FETCH_MODE = $save;
 736          
 737          if ( $forceAlter == false && empty($cols)) { // GS Fix for constraint impl
 738              return $this->CreateTableSQL($tablename, $flds, $tableoptions);
 739          }
 740          
 741          if (is_array($flds)) {
 742          // Cycle through the update fields, comparing
 743          // existing fields to fields to update.
 744          // if the Metatype and size is exactly the
 745          // same, ignore - by Mark Newham
 746              $holdflds = array();
 747              foreach($flds as $k=>$v) {
 748                  if ( isset($cols[$k]) && is_object($cols[$k]) ) {
 749                      // If already not allowing nulls, then don't change
 750                      $obj = $cols[$k];
 751                      if (isset($obj->not_null) && $obj->not_null)
 752                          $v = str_replace('NOT NULL','',$v);
 753  
 754                      $c = $cols[$k];
 755                      $ml = $c->max_length;
 756                      $mt = $this->MetaType($c->type,$ml);
 757                      if ($ml == -1) $ml = '';
 758                      if ($mt == 'X') $ml = $v['SIZE'];
 759                      if (($mt != $v['TYPE']) ||  $ml != $v['SIZE']) {
 760                          $holdflds[$k] = $v;
 761                      }
 762                  } else {
 763                      $holdflds[$k] = $v;
 764                  }        
 765              }
 766              $flds = $holdflds;
 767          }
 768      
 769  
 770          // already exists, alter table instead
 771          list($lines,$pkey) = $this->_GenFields($flds);
 772          $alter = 'ALTER TABLE ' . $this->TableName($tablename);
 773          $sql = array();
 774  
 775          foreach ( $lines as $id => $v ) {
 776              if ( isset($cols[$id]) && is_object($cols[$id]) ) {
 777              
 778                  $flds = Lens_ParseArgs($v,',');
 779                  
 780                  //  We are trying to change the size of the field, if not allowed, simply ignore the request.
 781                  if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)) continue;     
 782               
 783                  $sql[] = $alter . $this->alterCol . ' ' . $v;
 784              } else {
 785                  $sql[] = $alter . $this->addCol . ' ' . $v;
 786              }
 787          }
 788  
 789          // GS Fix for constraint impl -- start
 790          if($forceAlter == false) return $sql;
 791          $sqlarray = array();
 792  
 793          $alter .= implode(",\n", $sql);
 794          if (sizeof($pkey)>0) {
 795              $alter .= ",\n PRIMARY KEY (";
 796              $alter .= implode(", ",$pkey).")";
 797          }
 798          
 799          if (isset($tableoptions['CONSTRAINTS'])) 
 800              $alter .= "\n".$tableoptions['CONSTRAINTS'];
 801  
 802          if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
 803              $alter .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
 804  
 805          if (isset($tableoptions[$this->upperName])) $alter .= $tableoptions[$this->upperName];
 806              $sqlarray[] = $alter;
 807  
 808          
 809          $taboptions = $this->_Options($tableoptions);
 810          $tsql = $this->_Triggers($this->TableName($tablename),$taboptions);
 811          foreach($tsql as $s) $sqlarray[] = $s;
 812  
 813          // GS Fix for constraint impl -- end
 814          
 815          return $sqlarray;
 816  
 817          
 818      }
 819  } // class
 820  ?>


Généré le : Sun Feb 25 10:22:19 2007 par Balluche grâce à PHPXref 0.7