Initial commit

This commit is contained in:
Nathan Adams
2013-07-20 17:41:56 -05:00
commit 3b1e713fc4
606 changed files with 136001 additions and 0 deletions

112
pluf/src/Pluf/DB/Field.php Normal file
View File

@@ -0,0 +1,112 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* Default database field.
*/
class Pluf_DB_Field
{
/**
* The types are defined in the $mappings member variable of the
* schema class of your database engine, for example
* Pluf_DB_Schema_MySQL.
*/
public $type = '';
/**
* The column name of the field.
*/
public $column = '';
/**
* Current value of the field.
*/
public $value;
/**
* All the extra parameters of the field.
*/
public $extra = array();
/**
* The extra methods added to the model by the field.
*/
public $methods = array();
/**
* Constructor.
*
* @param mixed Value ('')
* @param string Column name ('')
*/
function __construct($value='', $column='', $extra=array())
{
$this->value = $value;
$this->column = $column;
if ($extra) {
$this->extra = array_merge($this->extra, $extra);
}
}
/**
* Get the form field for this field.
*
* We put this method at the field level as it allows us to easily
* create a new DB field and a new Form field and use them without
* the need to modify another place where the mapping would be
* performed.
*
* @param array Definition of the field.
* @param string Form field class.
*/
function formField($def, $form_field='Pluf_Form_Field_Varchar')
{
Pluf::loadClass('Pluf_Form_BoundField'); // To get mb_ucfirst
$defaults = array('required' => !$def['blank'],
'label' => mb_ucfirst($def['verbose']),
'help_text' => $def['help_text']);
unset($def['blank'], $def['verbose'], $def['help_text']);
if (isset($def['default'])) {
$defaults['initial'] = $def['default'];
unset($def['default']);
}
if (isset($def['choices'])) {
$defaults['widget'] = 'Pluf_Form_Widget_SelectInput';
if (isset($def['widget_attrs'])) {
$def['widget_attrs']['choices'] = $def['choices'];
} else {
$def['widget_attrs'] = array('choices' => $def['choices']);
}
}
foreach (array_keys($def) as $key) {
if (!in_array($key, array('widget', 'label', 'required', 'multiple',
'initial', 'choices', 'widget_attrs'))) {
unset($def[$key]);
}
}
$params = array_merge($defaults, $def);
return new $form_field($params);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Boolean extends Pluf_DB_Field
{
public $type = 'boolean';
function formField($def, $form_field='Pluf_Form_Field_Boolean')
{
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,42 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* This field will automatically inflate/deflate its content.
*
* This can be used to store large text bodies where you do not need
* to directly search into the content using the standard SQL
* functions.
*/
class Pluf_DB_Field_Compressed extends Pluf_DB_Field
{
public $type = 'blob';
function formField($def, $form_field='Pluf_Form_Field_Varchar')
{
if (!isset($def['widget'])) {
$def['widget'] = 'Pluf_Form_Widget_TextareaInput';
}
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Date extends Pluf_DB_Field
{
public $type = 'date';
function formField($def, $form_field='Pluf_Form_Field_Date')
{
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Datetime extends Pluf_DB_Field
{
public $type = 'datetime';
function formField($def, $form_field='Pluf_Form_Field_Datetime')
{
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,33 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Email extends Pluf_DB_Field
{
public $type = 'varchar';
public $extra = array('size' => 200);
function formField($def, $form_field='Pluf_Form_Field_Email')
{
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,76 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_File extends Pluf_DB_Field
{
/**
* See definition in Pluf_DB_Field.
*/
public $type = 'file';
public $column = '';
public $value;
public $extra = array();
public $methods = array();
/**
* Constructor.
*
* @param mixed Value ('')
* @param string Column name ('')
*/
function __construct($value='', $column='', $extra=array())
{
parent::__construct($value, $column, $extra);
$this->methods = array(array(strtolower($column).'_url', 'Pluf_DB_Field_File_Url'),
array(strtolower($column).'_path', 'Pluf_DB_Field_File_Path')
);
}
function formField($def, $form_field='Pluf_Form_Field_File')
{
return parent::formField($def, $form_field);
}
}
/**
* Returns the url to access the file.
*/
function Pluf_DB_Field_File_Url($field, $method, $model, $args=null)
{
if (strlen($model->$field) != 0) {
return Pluf::f('upload_url').'/'.$model->$field;
}
return '';
}
/**
* Returns the path to access the file.
*/
function Pluf_DB_Field_File_Path($field, $method, $model, $args=null)
{
if (strlen($model->$field) != 0) {
return Pluf::f('upload_path').'/'.$model->$field;
}
return '';
}

View File

@@ -0,0 +1,27 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Float extends Pluf_DB_Field
{
public $type = 'float';
}

View File

@@ -0,0 +1,38 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Foreignkey extends Pluf_DB_Field
{
public $type = 'foreignkey';
function formField($def, $form_field='Pluf_Form_Field_Varchar')
{
$gmodel = new $def['model']();
$choices = array();
foreach ($gmodel->getList() as $item) {
$choices[(string) $item] = $item->id;
}
$def['choices'] = $choices;
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,27 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Integer extends Pluf_DB_Field
{
public $type = 'integer';
}

View File

@@ -0,0 +1,45 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Manytomany extends Pluf_DB_Field
{
public $type = 'manytomany';
function formField($def, $form_field='Pluf_Form_Field_Integer')
{
$method = 'get_'.$def['name'].'_list';
$def['multiple'] = true;
$def['initial'] = array();
foreach ($def['model_instance']->$method() as $item) {
$def['initial'][(string) $item] = $item->id;
}
$def['choices'] = array();
foreach (Pluf::factory($def['model'])->getList() as $item) {
$def['choices'][(string) $item] = $item->id;
}
if (!isset($def['widget'])) {
$def['widget'] = 'Pluf_Form_Widget_SelectMultipleInput';
}
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,33 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Password extends Pluf_DB_Field
{
public $type = 'varchar';
function formField($def, $form_field='Pluf_Form_Field_Varchar')
{
$def['widget'] = 'Pluf_Form_Widget_PasswordInput';
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,36 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Sequence extends Pluf_DB_Field
{
public $type = 'sequence';
/**
* It is never possible to manually set the id of a model, this
* should be passed through the URL.
*/
function formField($def, $form_field='')
{
return null;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Serialized extends Pluf_DB_Field
{
public $type = 'text';
function formField($def, $form_field='Pluf_Form_Field_Varchar')
{
if (!isset($def['widget'])) {
$def['widget'] = 'Pluf_Form_Widget_TextareaInput';
}
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2010 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* This field will automatically slugify its content.
*
* A slug is a short label for something, containing only letters,
* numbers, underscores or hyphens. They're generally used in URLs.
*
* In your model, you can specify `max_length` in the `widget_attrs`
* parameter. If `max_length` is not specified, Pluf will use a
* default length of 50.
*/
class Pluf_DB_Field_Slug extends Pluf_DB_Field
{
public $type = 'varchar';
/**
* @see Pluf_DB_Field::formField()
*/
function formField($def, $form_field = 'Pluf_Form_Field_Slug')
{
return parent::formField($def, $form_field);
}
/**
* Return a "URL friendly" version in lowercase.
*
* Define the words separator with the configuration
* option <code>slug-separator</code>. Default to <code>-</code>.
*
* @param $value string Value to convert
* @return string The slugify version.
*/
public static function slugify($value)
{
$separator = Pluf::f('slug-separator', '-');
$value = Pluf_Text_UTF8::romanize(Pluf_Text_UTF8::deaccent($value));
$value = preg_replace('#[^'.$separator.'\w]#u',
$separator,
mb_strtolower($value, Pluf::f('encoding', 'UTF-8')));
// remove redundant
$value = preg_replace('#'.$separator.'{2,}#u',
$separator,
trim($value, $separator));
return $value;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Text extends Pluf_DB_Field
{
public $type = 'text';
function formField($def, $form_field='Pluf_Form_Field_Varchar')
{
if (!isset($def['widget'])) {
$def['widget'] = 'Pluf_Form_Widget_TextareaInput';
}
return parent::formField($def, $form_field);
}
}

View File

@@ -0,0 +1,27 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Field_Varchar extends Pluf_DB_Field
{
public $type = 'varchar';
}

View File

@@ -0,0 +1,52 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Introspect
{
protected $int = null;
protected $backend = '';
public function __construct($db)
{
$this->int = Pluf::factory('Pluf_DB_Introspect_'.$db->engine, $db);
$this->backend = $db->engine;
}
/**
* Get the list of tables in the current database. The search
* automatically limit the list to the visible ones.
*
* @param object DB connection.
* @return array List of tables.
*/
function listTables()
{
if (!method_exists($this->int, 'listTables')) {
throw new Pluf_Exception_NotImplemented();
}
return $this->int->listTables();
}
}

View File

@@ -0,0 +1,50 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Introspect_MySQL
{
protected $db = null;
public function __construct($db)
{
$this->db = $db;
}
/**
* Get the list of tables in the current database.
*
* @param object DB connection.
* @return array List of tables.
*/
function listTables()
{
$sql = 'SHOW TABLES';
$res = $this->db->select($sql);
$tables = array();
foreach ($res as $t) {
$tables[] = array_pop($t);
}
return $tables;
}
}

View File

@@ -0,0 +1,56 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_Introspect_PostgreSQL
{
protected $db = null;
public function __construct($db)
{
$this->db = $db;
}
/**
* Get the list of tables in the current database. The search
* automatically limit the list to the visible ones.
*
* @param object DB connection.
* @return array List of tables.
*/
function listTables()
{
$sql = 'SELECT c.relname AS name
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN (\'r\', \'v\', \'\')
AND n.nspname NOT IN (\'pg_catalog\', \'pg_toast\')
AND pg_catalog.pg_table_is_visible(c.oid)';
$res = $this->db->select($sql);
$tables = array();
foreach ($res as $t) {
$tables[] = $t['name'];
}
return $tables;
}
}

202
pluf/src/Pluf/DB/MySQL.php Normal file
View File

@@ -0,0 +1,202 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* MySQL connection class
*/
class Pluf_DB_MySQL
{
public $con_id;
public $pfx = '';
private $debug = true;
/** The last query, set with debug(). Used when an error is returned. */
public $lastquery = '';
public $engine = 'MySQL';
public $type_cast = array();
function __construct($user, $pwd, $server, $dbname, $pfx='', $debug=false)
{
Pluf::loadFunction('Pluf_DB_defaultTypecast');
$this->type_cast = Pluf_DB_defaultTypecast();
$this->debug('* MYSQL CONNECT');
$this->con_id = mysql_connect($server, $user, $pwd);
$this->debug = $debug;
$this->pfx = $pfx;
if (!$this->con_id) {
throw new Exception($this->getError());
}
$this->database($dbname);
$this->execute('SET NAMES \'utf8\'');
}
function database($dbname)
{
$db = mysql_select_db($dbname);
$this->debug('* USE DATABASE '.$dbname);
if (!$db) {
throw new Exception($this->getError());
}
return true;
}
/**
* Get the version of the MySQL server.
*
* @return string Version string
*/
function getServerInfo()
{
return mysql_get_server_info($this->con_id);
}
/**
* Log the queries. Keep track of the last query and if in debug mode
* keep track of all the queries in
* $GLOBALS['_PX_debug_data']['sql_queries']
*
* @param string Query to keep track
* @return bool true
*/
function debug($query)
{
$this->lastquery = $query;
if (!$this->debug) return true;
if (!isset($GLOBALS['_PX_debug_data']['sql_queries']))
$GLOBALS['_PX_debug_data']['sql_queries'] = array();
$GLOBALS['_PX_debug_data']['sql_queries'][] = $query;
return true;
}
function close()
{
if ($this->con_id) {
mysql_close($this->con_id);
return true;
} else {
return false;
}
}
function select($query)
{
$this->debug($query);
$cur = mysql_query($query, $this->con_id);
if ($cur) {
$res = array();
while ($row = mysql_fetch_assoc($cur)) {
$res[] = $row;
}
mysql_free_result($cur);
return $res;
} else {
throw new Exception($this->getError());
}
}
function execute($query)
{
$this->debug($query);
$cur = mysql_query($query, $this->con_id);
if (!$cur) {
throw new Exception($this->getError());
} else {
return true;
}
}
function getLastID()
{
$this->debug('* GET LAST ID');
return (int) mysql_insert_id($this->con_id);
}
/**
* Returns a string ready to be used in the exception.
*
* @return string Error string
*/
function getError()
{
if ($this->con_id) {
return mysql_errno($this->con_id).' - '
.mysql_error($this->con_id).' - '.$this->lastquery;
} else {
return mysql_errno().' - '
.mysql_error().' - '.$this->lastquery;
}
}
function esc($str)
{
return '\''.mysql_real_escape_string($str, $this->con_id).'\'';
}
/**
* Quote the column name.
*
* @param string Name of the column
* @return string Escaped name
*/
function qn($col)
{
return '`'.$col.'`';
}
/**
* Start a transaction.
*/
function begin()
{
if (Pluf::f('db_mysql_transaction', false)) {
$this->execute('BEGIN');
}
}
/**
* Commit a transaction.
*/
function commit()
{
if (Pluf::f('db_mysql_transaction', false)) {
$this->execute('COMMIT');
}
}
/**
* Rollback a transaction.
*/
function rollback()
{
if (Pluf::f('db_mysql_transaction', false)) {
$this->execute('ROLLBACK');
}
}
function __toString()
{
return '<Pluf_DB_MySQL('.$this->con_id.')>';
}
}

View File

@@ -0,0 +1,271 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* PostgreSQL connection class
*/
class Pluf_DB_PostgreSQL
{
/**
* The connection resource.
*/
public $con_id;
/**
* The prefix for the table names.
*/
public $pfx = '';
/**
* Debug mode.
*/
private $debug = false;
/**
* The last query, set with debug(). Used when an error is
* returned.
*/
public $lastquery = '';
/**
* Name of the engine.
*/
public $engine = 'PostgreSQL';
/**
* Used by the model to convert the values from and to the
* database.
*
* @see Pluf_DB_defaultTypecast
*/
public $type_cast = array();
/**
* Current query cursor.
*/
private $cur = null;
/**
* Current search path.
*/
public $search_path = 'public';
function __construct($user, $pwd, $server, $dbname, $pfx='', $debug=false)
{
Pluf::loadFunction('Pluf_DB_defaultTypecast');
$this->type_cast = Pluf_DB_defaultTypecast();
$this->type_cast['Pluf_DB_Field_Boolean'] =
array('Pluf_DB_PostgreSQL_BooleanFromDb', 'Pluf_DB_BooleanToDb');
$this->type_cast['Pluf_DB_Field_Compressed'] =
array('Pluf_DB_PostgreSQL_CompressedFromDb', 'Pluf_DB_PostgreSQL_CompressedToDb');
$this->debug('* POSTGRESQL CONNECT');
$cstring = '';
if ($server) {
$cstring .= 'host='.$server.' ';
}
$cstring .= 'dbname='.$dbname.' user='.$user;
if ($pwd) {
$cstring .= ' password='.$pwd;
}
$this->debug = $debug;
$this->pfx = $pfx;
$this->cur = null;
$this->con_id = @pg_connect($cstring);
if (!$this->con_id) {
throw new Exception($this->getError());
}
}
/**
* Get the version of the PostgreSQL server.
*
* Requires PostgreSQL 7.4 or later.
*
* @return string Version string
*/
function getServerInfo()
{
$ver = pg_version($this->con_id);
return $ver['server'];
}
/**
* Log the queries. Keep track of the last query and if in debug mode
* keep track of all the queries in
* $GLOBALS['_PX_debug_data']['sql_queries']
*
* @param string Query to keep track
* @return bool true
*/
function debug($query)
{
$this->lastquery = $query;
if (!$this->debug) return true;
if (!isset($GLOBALS['_PX_debug_data']['sql_queries']))
$GLOBALS['_PX_debug_data']['sql_queries'] = array();
$GLOBALS['_PX_debug_data']['sql_queries'][] = $query;
return true;
}
function close()
{
if ($this->con_id) {
pg_close($this->con_id);
return true;
} else {
return false;
}
}
function select($query)
{
$this->debug($query);
$this->cur = @pg_query($this->con_id, $query);
if (!$this->cur) {
throw new Exception($this->getError());
}
$res = array();
while ($row = pg_fetch_assoc($this->cur)) {
$res[] = $row;
}
@pg_free_result($this->cur);
$this->cur = null;
return $res;
}
function execute($query)
{
$this->debug($query);
$this->cur = @pg_query($this->con_id, $query);
if (!$this->cur) {
throw new Exception($this->getError());
}
return true;
}
function getLastID()
{
$this->debug('* GET LAST ID');
$res = $this->select('SELECT lastval() AS last_id');
return (int) $res[0]['last_id'];
}
/**
* Returns a string ready to be used in the exception.
*
* @return string Error string
*/
function getError()
{
if ($this->cur) {
return pg_result_error($this->cur).' - '.$this->lastquery;
}
if ($this->con_id) {
return pg_last_error($this->con_id).' - '.$this->lastquery;
} else {
return pg_last_error().' - '.$this->lastquery;
}
}
function esc($str)
{
return '\''.pg_escape_string($this->con_id, $str).'\'';
}
/**
* Set the current search path.
*/
function setSearchPath($search_path='public')
{
if (preg_match('/[^\w\s\,]/', $search_path)) {
throw new Exception('The search path: "'.$search_path.'" is not valid.');
}
$this->execute('SET search_path TO '.$search_path);
$this->search_path = $search_path;
return true;
}
/**
* Quote the column name.
*
* @param string Name of the column
* @return string Escaped name
*/
function qn($col)
{
return '"'.$col.'"';
}
/**
* Start a transaction.
*/
function begin()
{
$this->execute('BEGIN');
}
/**
* Commit a transaction.
*/
function commit()
{
$this->execute('COMMIT');
}
/**
* Rollback a transaction.
*/
function rollback()
{
$this->execute('ROLLBACK');
}
function __toString()
{
return '<Pluf_DB_PostgreSQL('.$this->con_id.')>';
}
}
function Pluf_DB_PostgreSQL_BooleanFromDb($val)
{
if (!$val) {
return false;
}
return (strtolower(substr($val, 0, 1)) == 't');
}
function Pluf_DB_PostgreSQL_CompressedToDb($val, $con)
{
if (is_null($val)) {
return 'NULL';
}
return "'".pg_escape_bytea(gzdeflate($val, 9))."'";
}
function Pluf_DB_PostgreSQL_CompressedFromDb($val)
{
return ($val) ? gzinflate(pg_unescape_bytea($val)) : $val;
}

178
pluf/src/Pluf/DB/SQLite.php Normal file
View File

@@ -0,0 +1,178 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* SQLite connection class
*/
class Pluf_DB_SQLite
{
public $con_id;
public $pfx = '';
private $debug = false;
/** The last query, set with debug(). Used when an error is returned. */
public $lastquery = '';
public $engine = 'SQLite';
public $type_cast = array();
function __construct($user, $pwd, $server, $dbname, $pfx='', $debug=false)
{
Pluf::loadFunction('Pluf_DB_defaultTypecast');
$this->type_cast = Pluf_DB_defaultTypecast();
$this->debug = $debug;
$this->pfx = $pfx;
$this->debug('* SQLITE OPEN');
$this->type_cast['Pluf_DB_Field_Compressed'] = array('Pluf_DB_CompressedFromDb', 'Pluf_DB_SQLite_CompressedToDb');
// Connect and let the Exception be thrown in case of problem
try {
$this->con_id = new PDO('sqlite:'.$dbname);
} catch (PDOException $e) {
throw $e;
}
}
/**
* Get the version of the SQLite library.
*
* @return string Version string
*/
function getServerInfo()
{
return $this->con_id->getAttribute(PDO::ATTR_SERVER_INFO);
}
/**
* Log the queries. Keep track of the last query and if in debug mode
* keep track of all the queries in
* $GLOBALS['_PX_debug_data']['sql_queries']
*
* @param string Query to keep track
* @return bool true
*/
function debug($query)
{
$this->lastquery = $query;
if (!$this->debug) return true;
if (!isset($GLOBALS['_PX_debug_data']['sql_queries']))
$GLOBALS['_PX_debug_data']['sql_queries'] = array();
$GLOBALS['_PX_debug_data']['sql_queries'][] = $query;
return true;
}
function close()
{
$this->con_id = null;
return true;
}
function select($query)
{
$this->debug($query);
if (false === ($cur = $this->con_id->query($query))) {
throw new Exception($this->getError());
}
return $cur->fetchAll(PDO::FETCH_ASSOC);
}
function execute($query)
{
$this->debug($query);
if (false === ($cur = $this->con_id->exec($query))) {
throw new Exception($this->getError());
}
return $cur;
}
function getLastID()
{
$this->debug('* GET LAST ID');
return (int) $this->con_id->lastInsertId();;
}
/**
* Returns a string ready to be used in the exception.
*
* @return string Error string
*/
function getError()
{
$err = $this->con_id->errorInfo();
$err[] = $this->lastquery;
return implode(' - ', $err);
}
function esc($str)
{
return $this->con_id->quote($str);
}
/**
* Quote the column name.
*
* @param string Name of the column
* @return string Escaped name
*/
function qn($col)
{
return '"'.$col.'"';
}
/**
* Start a transaction.
*/
function begin()
{
$this->execute('BEGIN');
}
/**
* Commit a transaction.
*/
function commit()
{
$this->execute('COMMIT');
}
/**
* Rollback a transaction.
*/
function rollback()
{
$this->execute('ROLLBACK');
}
function __toString()
{
return '<Pluf_DB_SQLite('.$this->con_id.')>';
}
}
function Pluf_DB_SQLite_CompressedToDb($val, $con)
{
if (is_null($val)) {
return 'NULL';
}
return 'X'.$con->esc(bin2hex(gzdeflate($val, 9)));
}

156
pluf/src/Pluf/DB/Schema.php Normal file
View File

@@ -0,0 +1,156 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* Create the schema of a given Pluf_Model for a given database.
*/
class Pluf_DB_Schema
{
/**
* Database connection object.
*/
private $con = null;
/**
* Model from which the schema is generated.
*/
public $model = null;
/**
* Schema generator object corresponding to the database.
*/
public $schema = null;
function __construct($db, $model=null)
{
$this->con = $db;
$this->model = $model;
$this->schema = Pluf::factory('Pluf_DB_Schema_'.$db->engine, $db);
}
/**
* Get the schema generator.
*
* @return object Pluf_DB_Schema_XXXX
*/
function getGenerator()
{
return $this->schema;
}
/**
* Create the tables and indexes for the current model.
*
* @return mixed True if success or database error.
*/
function createTables()
{
$sql = $this->schema->getSqlCreate($this->model);
foreach ($sql as $k => $query) {
if (false === $this->con->execute($query)) {
throw new Exception($this->con->getError());
}
}
$sql = $this->schema->getSqlIndexes($this->model);
foreach ($sql as $k => $query) {
if (false === $this->con->execute($query)) {
throw new Exception($this->con->getError());
}
}
return true;
}
/**
* Creates the constraints for the current model.
* This should be done _after_ all tables of all models have been created.
*
* @throws Exception
*/
function createConstraints()
{
$sql = $this->schema->getSqlCreateConstraints($this->model);
foreach ($sql as $k => $query) {
if (false === $this->con->execute($query)) {
throw new Exception($this->con->getError());
}
}
}
/**
* Drop the tables and indexes for the current model.
*
* @return mixed True if success or database error.
*/
function dropTables()
{
$sql = $this->schema->getSqlDelete($this->model);
foreach ($sql as $k => $query) {
if (false === $this->con->execute($query)) {
throw new Exception($this->con->getError());
}
}
return true;
}
/**
* Drops the constraints for the current model.
* This should be done _before_ all tables of all models are dropped.
*
* @throws Exception
* @return boolean
*/
function dropConstraints()
{
$sql = $this->schema->getSqlDeleteConstraints($this->model);
foreach ($sql as $k => $query) {
if (false === $this->con->execute($query)) {
throw new Exception($this->con->getError());
}
}
return true;
}
/**
* Given a column name or a string with column names in the format
* "column1, column2, column3", returns the escaped correctly
* quoted column names. This is good for index creation.
*
* @param string Column
* @param Pluf_DB DB handler
* @return string Quoted for the DB column(s)
*/
public static function quoteColumn($col, $db)
{
if (false !== strpos($col, ',')) {
$cols = explode(',', $col);
} else {
$cols = array($col);
}
$res = array();
foreach ($cols as $col) {
$res[] = $db->qn(trim($col));
}
return implode(', ', $res);
}
}

View File

@@ -0,0 +1,319 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* Generator of the schemas corresponding to a given model.
*
* This class is for MySQL, you can create a class on the same
* model for another database engine.
*/
class Pluf_DB_Schema_MySQL
{
/**
* Mapping of the fields.
*/
public $mappings = array(
'varchar' => 'varchar(%s)',
'sequence' => 'mediumint(9) unsigned not null auto_increment',
'boolean' => 'bool',
'date' => 'date',
'datetime' => 'datetime',
'file' => 'varchar(150)',
'manytomany' => null,
'foreignkey' => 'mediumint(9) unsigned',
'text' => 'longtext',
'html' => 'longtext',
'time' => 'time',
'integer' => 'integer',
'email' => 'varchar(150)',
'password' => 'varchar(150)',
'float' => 'numeric(%s, %s)',
'blob' => 'blob',
);
public $defaults = array(
'varchar' => "''",
'sequence' => null,
'boolean' => 1,
'date' => 0,
'datetime' => 0,
'file' => "''",
'manytomany' => null,
'foreignkey' => 0,
'text' => "''",
'html' => "''",
'time' => 0,
'integer' => 0,
'email' => "''",
'password' => "''",
'float' => 0.0,
'blob' => "''",
);
private $con = null;
function __construct($con)
{
$this->con = $con;
}
/**
* Get the SQL to generate the tables of the given model.
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlCreate($model)
{
$tables = array();
$cols = $model->_a['cols'];
$manytomany = array();
$sql = 'CREATE TABLE `'.$this->con->pfx.$model->_a['table'].'` (';
foreach ($cols as $col => $val) {
$field = new $val['type']();
if ($field->type != 'manytomany') {
$sql .= "\n".$this->con->qn($col).' ';
$_tmp = $this->mappings[$field->type];
if ($field->type == 'varchar') {
if (isset($val['size'])) {
$_tmp = sprintf($this->mappings['varchar'], $val['size']);
} else {
$_tmp = sprintf($this->mappings['varchar'], '150');
}
}
if ($field->type == 'float') {
if (!isset($val['max_digits'])) {
$val['max_digits'] = 32;
}
if (!isset($val['decimal_places'])) {
$val['decimal_places'] = 8;
}
$_tmp = sprintf($this->mappings['float'], $val['max_digits'], $val['decimal_places']);
}
$sql .= $_tmp;
if (empty($val['is_null'])) {
$sql .= ' NOT NULL';
}
if (isset($val['default'])) {
$sql .= ' default ';
$sql .= $model->_toDb($val['default'], $col);
} elseif ($field->type != 'sequence') {
$sql .= ' default '.$this->defaults[$field->type];
}
$sql .= ',';
} else {
$manytomany[] = $col;
}
}
$sql .= "\n".'PRIMARY KEY (`id`))';
$sql .= 'ENGINE=InnoDB DEFAULT CHARSET=utf8;';
$tables[$this->con->pfx.$model->_a['table']] = $sql;
// Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $hay[0].'_'.$hay[1].'_assoc';
$sql = 'CREATE TABLE `'.$this->con->pfx.$table.'` (';
$sql .= "\n".'`'.strtolower($model->_a['model']).'_id` '.$this->mappings['foreignkey'].' default 0,';
$sql .= "\n".'`'.strtolower($omodel->_a['model']).'_id` '.$this->mappings['foreignkey'].' default 0,';
$sql .= "\n".'PRIMARY KEY ('.strtolower($model->_a['model']).'_id, '.strtolower($omodel->_a['model']).'_id)';
$sql .= "\n".') ENGINE=InnoDB';
$sql .=' DEFAULT CHARSET=utf8;';
$tables[$this->con->pfx.$table] = $sql;
}
return $tables;
}
/**
* Get the SQL to generate the indexes of the given model.
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlIndexes($model)
{
$index = array();
foreach ($model->_a['idx'] as $idx => $val) {
if (!isset($val['col'])) {
$val['col'] = $idx;
}
$index[$this->con->pfx.$model->_a['table'].'_'.$idx] =
sprintf('CREATE INDEX `%s` ON `%s` (%s);',
$idx, $this->con->pfx.$model->_a['table'],
Pluf_DB_Schema::quoteColumn($val['col'], $this->con));
}
foreach ($model->_a['cols'] as $col => $val) {
$field = new $val['type']();
if ($field->type == 'foreignkey') {
$index[$this->con->pfx.$model->_a['table'].'_'.$col.'_foreignkey'] =
sprintf('CREATE INDEX `%s` ON `%s` (`%s`);',
$col.'_foreignkey_idx', $this->con->pfx.$model->_a['table'], $col);
}
if (isset($val['unique']) and $val['unique'] == true) {
$index[$this->con->pfx.$model->_a['table'].'_'.$col.'_unique'] =
sprintf('CREATE UNIQUE INDEX `%s` ON `%s` (%s);',
$col.'_unique_idx',
$this->con->pfx.$model->_a['table'],
Pluf_DB_Schema::quoteColumn($col, $this->con)
);
}
}
return $index;
}
/**
* Workaround for <http://bugs.mysql.com/bug.php?id=13942> which limits the
* length of foreign key identifiers to 64 characters.
*
* @param string
* @return string
*/
function getShortenedFKeyName($name)
{
if (strlen($name) <= 64) {
return $name;
}
return substr($name, 0, 55).'_'.substr(md5($name), 0, 8);
}
/**
* Get the SQL to create the constraints for the given model
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlCreateConstraints($model)
{
$table = $this->con->pfx.$model->_a['table'];
$constraints = array();
$alter_tbl = 'ALTER TABLE '.$table;
$cols = $model->_a['cols'];
$manytomany = array();
foreach ($cols as $col => $val) {
$field = new $val['type']();
// remember these for later
if ($field->type == 'manytomany') {
$manytomany[] = $col;
}
if ($field->type == 'foreignkey') {
// Add the foreignkey constraints
$referto = new $val['model']();
$constraints[] = $alter_tbl.' ADD CONSTRAINT '.$this->getShortenedFKeyName($table.'_'.$col.'_fkey').'
FOREIGN KEY ('.$this->con->qn($col).')
REFERENCES '.$this->con->pfx.$referto->_a['table'].' (id)
ON DELETE NO ACTION ON UPDATE NO ACTION';
}
}
// Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $this->con->pfx.$hay[0].'_'.$hay[1].'_assoc';
$alter_tbl = 'ALTER TABLE '.$table;
$constraints[] = $alter_tbl.' ADD CONSTRAINT '.$this->getShortenedFKeyName($table.'_fkey1').'
FOREIGN KEY ('.strtolower($model->_a['model']).'_id)
REFERENCES '.$this->con->pfx.$model->_a['table'].' (id)
ON DELETE NO ACTION ON UPDATE NO ACTION';
$constraints[] = $alter_tbl.' ADD CONSTRAINT '.$this->getShortenedFKeyName($table.'_fkey2').'
FOREIGN KEY ('.strtolower($omodel->_a['model']).'_id)
REFERENCES '.$this->con->pfx.$omodel->_a['table'].' (id)
ON DELETE NO ACTION ON UPDATE NO ACTION';
}
return $constraints;
}
/**
* Get the SQL to drop the tables corresponding to the model.
*
* @param Object Model
* @return string SQL string ready to execute.
*/
function getSqlDelete($model)
{
$cols = $model->_a['cols'];
$manytomany = array();
$sql = 'DROP TABLE IF EXISTS `'.$this->con->pfx.$model->_a['table'].'`';
foreach ($cols as $col => $val) {
$field = new $val['type']();
if ($field->type == 'manytomany') {
$manytomany[] = $col;
}
}
//Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $hay[0].'_'.$hay[1].'_assoc';
$sql .= ', `'.$this->con->pfx.$table.'`';
}
return array($sql);
}
/**
* Get the SQL to drop the constraints for the given model
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlDeleteConstraints($model)
{
$table = $this->con->pfx.$model->_a['table'];
$constraints = array();
$alter_tbl = 'ALTER TABLE '.$table;
$cols = $model->_a['cols'];
$manytomany = array();
foreach ($cols as $col => $val) {
$field = new $val['type']();
// remember these for later
if ($field->type == 'manytomany') {
$manytomany[] = $col;
}
if ($field->type == 'foreignkey') {
// Add the foreignkey constraints
$referto = new $val['model']();
$constraints[] = $alter_tbl.' DROP CONSTRAINT '.$this->getShortenedFKeyName($table.'_'.$col.'_fkey');
}
}
// Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $this->con->pfx.$hay[0].'_'.$hay[1].'_assoc';
$alter_tbl = 'ALTER TABLE '.$table;
$constraints[] = $alter_tbl.' DROP CONSTRAINT '.$this->getShortenedFKeyName($table.'_fkey1');
$constraints[] = $alter_tbl.' DROP CONSTRAINT '.$this->getShortenedFKeyName($table.'_fkey2');
}
return $constraints;
}
}

View File

@@ -0,0 +1,308 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* Generator of the schemas corresponding to a given model.
*
* This class is for PostgreSQL, you can create a class on the same
* model for another database engine.
*/
class Pluf_DB_Schema_PostgreSQL
{
/**
* Mapping of the fields.
*/
public $mappings = array(
'varchar' => 'character varying',
'sequence' => 'serial',
'boolean' => 'boolean',
'date' => 'date',
'datetime' => 'timestamp',
'file' => 'character varying',
'manytomany' => null,
'foreignkey' => 'integer',
'text' => 'text',
'html' => 'text',
'time' => 'time',
'integer' => 'integer',
'email' => 'character varying',
'password' => 'character varying',
'float' => 'real',
'blob' => 'bytea',
);
public $defaults = array(
'varchar' => "''",
'sequence' => null,
'boolean' => 'FALSE',
'date' => "'0001-01-01'",
'datetime' => "'0001-01-01 00:00:00'",
'file' => "''",
'manytomany' => null,
'foreignkey' => 0,
'text' => "''",
'html' => "''",
'time' => "'00:00:00'",
'integer' => 0,
'email' => "''",
'password' => "''",
'float' => 0.0,
'blob' => "''",
);
private $con = null;
function __construct($con)
{
$this->con = $con;
}
/**
* Get the SQL to generate the tables of the given model.
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlCreate($model)
{
$tables = array();
$cols = $model->_a['cols'];
$manytomany = array();
$query = 'CREATE TABLE '.$this->con->pfx.$model->_a['table'].' (';
$sql_col = array();
foreach ($cols as $col => $val) {
$field = new $val['type']();
if ($field->type != 'manytomany') {
$sql = $this->con->qn($col).' ';
$sql .= $this->mappings[$field->type];
if (empty($val['is_null'])) {
$sql .= ' NOT NULL';
}
if (isset($val['default'])) {
$sql .= ' default ';
$sql .= $model->_toDb($val['default'], $col);
} elseif ($field->type != 'sequence') {
$sql .= ' default '.$this->defaults[$field->type];
}
$sql_col[] = $sql;
} else {
$manytomany[] = $col;
}
}
$sql_col[] = 'CONSTRAINT '.$this->con->pfx.$model->_a['table'].'_pkey PRIMARY KEY (id)';
$query = $query."\n".implode(",\n", $sql_col)."\n".');';
$tables[$this->con->pfx.$model->_a['table']] = $query;
// Now for the many to many
// FIXME add index on the second column
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $hay[0].'_'.$hay[1].'_assoc';
$sql = 'CREATE TABLE '.$this->con->pfx.$table.' (';
$sql .= "\n".strtolower($model->_a['model']).'_id '.$this->mappings['foreignkey'].' default 0,';
$sql .= "\n".strtolower($omodel->_a['model']).'_id '.$this->mappings['foreignkey'].' default 0,';
$sql .= "\n".'CONSTRAINT '.$this->getShortenedIdentifierName($this->con->pfx.$table.'_pkey').' PRIMARY KEY ('.strtolower($model->_a['model']).'_id, '.strtolower($omodel->_a['model']).'_id)';
$sql .= "\n".');';
$tables[$this->con->pfx.$table] = $sql;
}
return $tables;
}
/**
* Get the SQL to generate the indexes of the given model.
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlIndexes($model)
{
$index = array();
foreach ($model->_a['idx'] as $idx => $val) {
if (!isset($val['col'])) {
$val['col'] = $idx;
}
if ($val['type'] == 'unique') {
$unique = 'UNIQUE ';
} else {
$unique = '';
}
$index[$this->con->pfx.$model->_a['table'].'_'.$idx] =
sprintf('CREATE '.$unique.'INDEX %s ON %s (%s);',
$this->con->pfx.$model->_a['table'].'_'.$idx,
$this->con->pfx.$model->_a['table'],
Pluf_DB_Schema::quoteColumn($val['col'], $this->con)
);
}
foreach ($model->_a['cols'] as $col => $val) {
$field = new $val['type']();
if (isset($val['unique']) and $val['unique'] == true) {
$index[$this->con->pfx.$model->_a['table'].'_'.$col.'_unique'] =
sprintf('CREATE UNIQUE INDEX %s ON %s (%s);',
$this->con->pfx.$model->_a['table'].'_'.$col.'_unique_idx',
$this->con->pfx.$model->_a['table'],
Pluf_DB_Schema::quoteColumn($col, $this->con)
);
}
}
return $index;
}
/**
* All identifiers in Postgres must not exceed 64 characters in length.
*
* @param string
* @return string
*/
function getShortenedIdentifierName($name)
{
if (strlen($name) <= 64) {
return $name;
}
return substr($name, 0, 55).'_'.substr(md5($name), 0, 8);
}
/**
* Get the SQL to create the constraints for the given model
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlCreateConstraints($model)
{
$table = $this->con->pfx.$model->_a['table'];
$constraints = array();
$alter_tbl = 'ALTER TABLE '.$table;
$cols = $model->_a['cols'];
$manytomany = array();
foreach ($cols as $col => $val) {
$field = new $val['type']();
// remember these for later
if ($field->type == 'manytomany') {
$manytomany[] = $col;
}
if ($field->type == 'foreignkey') {
// Add the foreignkey constraints
$referto = new $val['model']();
$constraints[] = $alter_tbl.' ADD CONSTRAINT '.$this->getShortenedIdentifierName($table.'_'.$col.'_fkey').'
FOREIGN KEY ('.$this->con->qn($col).')
REFERENCES '.$this->con->pfx.$referto->_a['table'].' (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION';
}
}
// Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $this->con->pfx.$hay[0].'_'.$hay[1].'_assoc';
$alter_tbl = 'ALTER TABLE '.$table;
$constraints[] = $alter_tbl.' ADD CONSTRAINT '.$this->getShortenedIdentifierName($table.'_fkey1').'
FOREIGN KEY ('.strtolower($model->_a['model']).'_id)
REFERENCES '.$this->con->pfx.$model->_a['table'].' (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION';
$constraints[] = $alter_tbl.' ADD CONSTRAINT '.$this->getShortenedIdentifierName($table.'_fkey2').'
FOREIGN KEY ('.strtolower($omodel->_a['model']).'_id)
REFERENCES '.$this->con->pfx.$omodel->_a['table'].' (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION';
}
return $constraints;
}
/**
* Get the SQL to drop the tables corresponding to the model.
*
* @param Object Model
* @return string SQL string ready to execute.
*/
function getSqlDelete($model)
{
$cols = $model->_a['cols'];
$manytomany = array();
$sql = array();
$sql[] = 'DROP TABLE IF EXISTS '.$this->con->pfx.$model->_a['table'].' CASCADE';
foreach ($cols as $col => $val) {
$field = new $val['type']();
if ($field->type == 'manytomany') {
$manytomany[] = $col;
}
}
//Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $hay[0].'_'.$hay[1].'_assoc';
$sql[] = 'DROP TABLE IF EXISTS '.$this->con->pfx.$table.' CASCADE';
}
return $sql;
}
/**
* Get the SQL to drop the constraints for the given model
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlDeleteConstraints($model)
{
$table = $this->con->pfx.$model->_a['table'];
$constraints = array();
$alter_tbl = 'ALTER TABLE '.$table;
$cols = $model->_a['cols'];
$manytomany = array();
foreach ($cols as $col => $val) {
$field = new $val['type']();
// remember these for later
if ($field->type == 'manytomany') {
$manytomany[] = $col;
}
if ($field->type == 'foreignkey') {
// Add the foreignkey constraints
$referto = new $val['model']();
$constraints[] = $alter_tbl.' DROP CONSTRAINT '.$this->getShortenedIdentifierName($table.'_'.$col.'_fkey');
}
}
// Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $this->con->pfx.$hay[0].'_'.$hay[1].'_assoc';
$alter_tbl = 'ALTER TABLE '.$table;
$constraints[] = $alter_tbl.' DROP CONSTRAINT '.$this->getShortenedIdentifierName($table.'_fkey1');
$constraints[] = $alter_tbl.' DROP CONSTRAINT '.$this->getShortenedIdentifierName($table.'_fkey2');
}
return $constraints;
}
}

View File

@@ -0,0 +1,246 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* Generator of the schemas corresponding to a given model.
*
* This class is for SQLite, you can create a class on the same
* model for another database engine.
*/
class Pluf_DB_Schema_SQLite
{
/**
* Mapping of the fields.
*/
public $mappings = array(
'varchar' => 'varchar(%s)',
'sequence' => 'integer primary key autoincrement',
'boolean' => 'bool',
'date' => 'date',
'datetime' => 'datetime',
'file' => 'varchar(150)',
'manytomany' => null,
'foreignkey' => 'integer',
'text' => 'text',
'html' => 'text',
'time' => 'time',
'integer' => 'integer',
'email' => 'varchar(150)',
'password' => 'varchar(150)',
'float' => 'real',
'blob' => 'blob',
);
public $defaults = array(
'varchar' => "''",
'sequence' => null,
'boolean' => 1,
'date' => 0,
'datetime' => 0,
'file' => "''",
'manytomany' => null,
'foreignkey' => 0,
'text' => "''",
'html' => "''",
'time' => 0,
'integer' => 0,
'email' => "''",
'password' => "''",
'float' => 0.0,
'blob' => "''",
);
private $con = null;
function __construct($con)
{
$this->con = $con;
}
/**
* Get the SQL to generate the tables of the given model.
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlCreate($model)
{
$tables = array();
$cols = $model->_a['cols'];
$manytomany = array();
$query = 'CREATE TABLE '.$this->con->pfx.$model->_a['table'].' (';
$sql_col = array();
foreach ($cols as $col => $val) {
$field = new $val['type']();
if ($field->type != 'manytomany') {
$sql = $this->con->qn($col).' ';
$_tmp = $this->mappings[$field->type];
if ($field->type == 'varchar') {
if (isset($val['size'])) {
$_tmp = sprintf($this->mappings['varchar'], $val['size']);
} else {
$_tmp = sprintf($this->mappings['varchar'], '150');
}
}
if ($field->type == 'float') {
if (!isset($val['max_digits'])) {
$val['max_digits'] = 32;
}
if (!isset($val['decimal_places'])) {
$val['decimal_places'] = 8;
}
$_tmp = sprintf($this->mappings['float'], $val['max_digits'], $val['decimal_places']);
}
$sql .= $_tmp;
if (empty($val['is_null'])) {
$sql .= ' not null';
}
if (isset($val['default'])) {
$sql .= ' default '.$model->_toDb($val['default'], $col);
} elseif ($field->type != 'sequence') {
$sql .= ' default '.$this->defaults[$field->type];
}
$sql_col[] = $sql;
} else {
$manytomany[] = $col;
}
}
$query = $query."\n".implode(",\n", $sql_col)."\n".');';
$tables[$this->con->pfx.$model->_a['table']] = $query;
//Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $hay[0].'_'.$hay[1].'_assoc';
$sql = 'CREATE TABLE '.$this->con->pfx.$table.' (';
$sql .= "\n".strtolower($model->_a['model']).'_id '.$this->mappings['foreignkey'].' default 0,';
$sql .= "\n".strtolower($omodel->_a['model']).'_id '.$this->mappings['foreignkey'].' default 0,';
$sql .= "\n".'primary key ('.strtolower($model->_a['model']).'_id, '.strtolower($omodel->_a['model']).'_id)';
$sql .= "\n".');';
$tables[$this->con->pfx.$table] = $sql;
}
return $tables;
}
/**
* SQLite cannot add foreign key constraints to already existing tables,
* so we skip their creation completely.
*
* @param Object Model
* @return array
*/
function getSqlCreateConstraints($model)
{
return array();
}
/**
* Get the SQL to generate the indexes of the given model.
*
* @param Object Model
* @return array Array of SQL strings ready to execute.
*/
function getSqlIndexes($model)
{
$index = array();
foreach ($model->_a['idx'] as $idx => $val) {
if (!isset($val['col'])) {
$val['col'] = $idx;
}
$unique = (isset($val['type']) && ($val['type'] == 'unique')) ? 'UNIQUE ' : '';
$index[$this->con->pfx.$model->_a['table'].'_'.$idx] =
sprintf('CREATE %sINDEX %s ON %s (%s);',
$unique,
$this->con->pfx.$model->_a['table'].'_'.$idx,
$this->con->pfx.$model->_a['table'],
Pluf_DB_Schema::quoteColumn($val['col'], $this->con)
);
}
foreach ($model->_a['cols'] as $col => $val) {
$field = new $val['type']();
if ($field->type == 'foreignkey') {
$index[$this->con->pfx.$model->_a['table'].'_'.$col.'_foreignkey'] =
sprintf('CREATE INDEX %s ON %s (%s);',
$this->con->pfx.$model->_a['table'].'_'.$col.'_foreignkey_idx',
$this->con->pfx.$model->_a['table'],
Pluf_DB_Schema::quoteColumn($col, $this->con));
}
if (isset($val['unique']) and $val['unique'] == true) {
$index[$this->con->pfx.$model->_a['table'].'_'.$col.'_unique'] =
sprintf('CREATE UNIQUE INDEX %s ON %s (%s);',
$this->con->pfx.$model->_a['table'].'_'.$col.'_unique_idx',
$this->con->pfx.$model->_a['table'],
Pluf_DB_Schema::quoteColumn($col, $this->con)
);
}
}
return $index;
}
/**
* Get the SQL to drop the tables corresponding to the model.
*
* @param Object Model
* @return string SQL string ready to execute.
*/
function getSqlDelete($model)
{
$cols = $model->_a['cols'];
$manytomany = array();
$sql = array();
$sql[] = 'DROP TABLE IF EXISTS '.$this->con->pfx.$model->_a['table'];
foreach ($cols as $col => $val) {
$field = new $val['type']();
if ($field->type == 'manytomany') {
$manytomany[] = $col;
}
}
//Now for the many to many
foreach ($manytomany as $many) {
$omodel = new $cols[$many]['model']();
$hay = array(strtolower($model->_a['model']), strtolower($omodel->_a['model']));
sort($hay);
$table = $hay[0].'_'.$hay[1].'_assoc';
$sql[] = 'DROP TABLE IF EXISTS '.$this->con->pfx.$table;
}
return $sql;
}
/**
* SQLite cannot drop foreign keys from existing tables,
* so we skip their deletion completely.
*
* @param Object Model
* @return array
*/
function getSqlDeleteConstraints($model)
{
return array();
}
}

View File

@@ -0,0 +1,53 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
class Pluf_DB_SchemaInfo extends Pluf_Model
{
public $_model = __CLASS__;
function init()
{
$this->_a['table'] = 'schema_info';
$this->_a['model'] = 'Pluf_DB_SchemaInfo';
$this->_a['cols'] = array(
// It is mandatory to have an "id" column.
'id' =>
array(
'type' => 'Pluf_DB_Field_Sequence',
//It is automatically added.
'blank' => true,
),
'application' =>
array(
'type' => 'Pluf_DB_Field_Varchar',
'blank' => false,
'unique' => true,
),
'version' =>
array(
'type' => 'Pluf_DB_Field_Integer',
'blank' => false,
),
);
}
}

View File

@@ -0,0 +1,84 @@
<?php
/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Plume Framework, a simple PHP Application Framework.
# Copyright (C) 2001-2010 Loic d'Anterroches and contributors.
#
# Plume Framework is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Plume Framework 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# ***** END LICENSE BLOCK ***** */
/**
* Database statistics class.
*
* This class is just a wrapper which will pass the queries to the
* underlying database class but keeping timing information. This is
* very good to track your slow queries and improve your code.
*
*/
class Pluf_DB_Stats
{
/**
* The real database connection.
*/
protected $_rdb = null;
public function __construct($db)
{
$this->_rdb = $db;
}
public function __call($name, $args)
{
if (!in_array($name, array('execute', 'select'))) {
return call_user_func_array(array($this->_rdb, $name), $args);
}
Pluf_Log::stime('timer');
$res = call_user_func_array(array($this->_rdb, $name), $args);
Pluf_Log::perf(array('Pluf_DB_Stats', $this->_rdb->lastquery, Pluf_Log::etime('timer', 'total_sql')));
Pluf_Log::inc('sql_query');
return $res;
}
public function __get($name)
{
return $this->_rdb->$name;
}
public function __set($name, $value)
{
return $this->_rdb->$name = $value;
}
}
function Pluf_DB_Stats_getConnection($extra=null)
{
if (isset($GLOBALS['_PX_db']) &&
(is_resource($GLOBALS['_PX_db']->con_id) or is_object($GLOBALS['_PX_db']->con_id))) {
return $GLOBALS['_PX_db'];
}
$GLOBALS['_PX_db'] = new Pluf_DB_Stats(
Pluf_DB::get(Pluf::f('db_engine'),
Pluf::f('db_server'),
Pluf::f('db_database'),
Pluf::f('db_login'),
Pluf::f('db_password'),
Pluf::f('db_table_prefix'),
Pluf::f('db_debug'),
Pluf::f('db_version'))
);
return $GLOBALS['_PX_db'];
}