MySQL- Руководство разработчика

         

Модуль MySQLDataset


Этот модуль содержит все классы необходимые, чтобы поддерживать основной класс TMySQLDataset.

Компонент: TMySQLDataset.

Типы: TMySQLEvent, TMySQLLocateOptions.

Константы: DefaultMacroChar='|', DefaultTermChar=';'.

TMySQLDataset

Модуль: MySQLDataset.

Описание

Это основной класс, используемый в Вашей прикладной программе. Он был назван именно Dataset, а не Query или Table потому, что он может легко использоваться как стандартный TTable или TQuery. Поскольку этот класс связывается и работает с сервером MySQL, он делает доступными для использования все инструкции SQL. По умолчанию используется концепция макросов (Macros) в командах SQL. Эти макрокоманды очень легко могут быть заблокированы или удалены из значения по умолчанию SQL.

Кроме того, являясь прямым поточным подключением к серверу MySQL, класс был получен непосредственно из TDataset и таким образом поддержан всеми компонентами для работы с базами данных, включая TDatasource. Этот компонент имеет все стандартные свойства и методы.

Из-за отсутствия поддержки курсоров на стороне сервера в MySQL, этот компонент полагается на хорошо разработанные таблицы по умолчанию, то есть Ваши таблицы должны по крайней мере иметь первичный ключ. Если Вы отменяете заданные по умолчанию инструкции SQL, Вы можете сами определять, когда, что и над чем будет выполнено.

Компонент TMySQLDataset

Свойства

Active!AL("Active_Property") AffectedRows AfterCancel!AL("AfterCancel_Property") AfterClose!AL("AfterClose_Property") AfterDelete!AL("AfterDelete_Property") AfterEdit!AL("AfterEdit_Property") AfterInsert!AL("AfterInsert_Property") AfterOpen!AL("AfterOpen_Property") AfterPost!AL("AfterPost_Property") AfterRefresh!AL("AfterRefresh_Property") AfterScroll!AL("AfterScroll_Property") BeforeCancel!AL("BeforeCancel_Property") BeforeClose!AL("BeforeClose_Property") BeforeDelete!AL("BeforeDelete_Property") BeforeEdit!AL("BeforeEdit_Property") BeforeInsert!AL("BeforeInsert_Property") BeforeOpen!AL("BeforeOpen_Property") BeforePost!AL("BeforePost_Property") BeforeRefresh!AL("BeforeRefresh_Property") BeforeScroll!AL("BeforeScroll_Property") AllFieldValues CachedUpdates DatabaseName FieldName Filter Filtered MacroChar MacroCount Macros MacrosEnabled MasterFields MasterSource MultiKeyFields MySQLFields MySQLRecords MySQLTables PrimaryKeyFields ReadOnly RealSQL Records Server ShareConnection SQL SQLBatch SQLDelete SQLInsert SQLUpdate TableName UniqueKeyFields


Методы

Create!AL("Create_Method") Destroy!AL("Destroy_Method") BookmarkValid!AL("BookmarkValid_Method") CompareBookmarks!AL("CompareBookmarks_Method") CreateBlobStream!AL("CreateBlobStream_Method") EscapeStr ExecBatch ExecSQL ExecSQLBatch GetFieldData!AL("GetFieldData_Method") GetMacroValue HexStr Locate!AL("Locate_Method") LocateRecord LocateRecordOption Lookup!AL("Lookup_Method") MacroByName ParseSQL QuoteStr ClearMacros ConnectEvent

События

OnCalcFields!AL("OnCalcFields_Event") OnDeleteError!AL("OnDeleteError_Event") OnEditError!AL("OnEditError_Event") OnExecSQL OnNewRecord!AL("OnNewRecord_Event") OnPostError!AL("OnPostError_Event")

Свойство AffectedRows

Применимо к TMySQLDataset

Определение

property AffectedRows : string;

Описание



Число строк, на которые воздействует последняя инструкция SQL, которая будет выполнена. Только для Run-time. Read-only.



Свойство CachedUpdates

Применимо к TMySQLDataset

Определение

property CachedUpdates : boolean;

Описание



Установка этого свойства в True заставит все инструкции SQL, SQLUpdate, SQLInsert, SQLDelete и SQLBatch кэшироваться на локальной системе и реально выполняться только тогда, когда методы Close или Refresh в очередной раз обращаются к этому набору данных.

Свойство DatabaseName

Применимо к TMySQLDataset

Определение

property DatabaseName : string;

Описание



В настоящее время выбранная база данных, устанавливая это свойство вызовет "USE Database" на активной поточной связи этого набора данных с сервером MySQL. Это значение заменит все макросы $DATABASENAME в Ваших запросах SQL.

Свойство FieldName

Применимо к TMySQLDataset

Определение

property FieldName : string;

Описание



В настоящее время выбранное имя поля (возможно, нескольких полей). Это может содержать список полей, разделенных запятыми, и необязательный первичный ключ для текущей (актуальной) таблицы. Это заменит все макросы $FIELDNAME в Ваших запросах SQL.



Свойство AllFieldValues

Применимо к TMySQLDataset

Определение

property AllFieldValues : boolean;

Описание



Установите это свойство в True, если Вы хотите, чтобы набор данных использовал "show columns from table", чтобы получить расширенную информацию относительно каждого поля, например, значения по умолчанию, перечни допустимых значений для полей типов ENUM и SET и так далее.

Свойство MacroChar

Применимо к TMySQLDataset

Определение

property MacroChar : Char;

Описание



Текущий (актуальный) символ, используемый для определенных макрокоманд в Ваших инструкциях SQL.

Свойство Filter

Применимо к MySQLDataset

Определение

property Filter : string;

Описание



Установите это свойство к любому имеющему силу определению MySQL WHERE, например, AccountName like "J%". Это значение будет автоматически включено в макрокоманду $WHERE, если Filtered установлено в значение True.

Свойство MacroCount

Применимо к TMySQLDataset

Определение

property MacroCount : Word;

Описание



Число существующих макрокоманд. Только Run-time. Read-only.

Свойство Filtered

Применимо к TMySQLDataset

Определение

property Filtered : boolean;

Описание



Установите это свойство в True, если Вы хотите, чтобы текущий (актуальный) Filter применялся со следующей командой Open к набору данных.

Свойство MasterFields

Применимо к TMySQLDataset

Определение

property MasterFields : string;

Описание



Установите это свойство к любой имеющей силу комбинации Name=Value так, чтобы получилась пара DetailField=MasterField, например, MasterFields:='AccountID=AccountID,AccountName=FirstName', или используйте компоновку, чтобы связать Ваш набор данных с полями MasterSource.

AccountID и AccountName берутся из текущего детального набора данных, а AccountID и Firstname берутся из главного набора данных, определенного свойством MasterSource.

Поля, определенные свойством MasterFields, автоматически анализируются и будут вставлены в предложение $WHERE, набор данных будет закрыт и вновь открыт, уже используя новую инструкцию SQL, которая отразит изменения в наборе данных MasterSource.



Свойство Macros

Применимо к TMySQLDataset

Определение

property Macros : TMySQLMacros;

Описание



TParams представляет собой совокупность макрокоманд, найденных в инструкциях SQL.

Свойство MasterSource

Применимо к TMySQLDataset

Определение

property MasterSource : string;

Описание



Установите это свойство к любому имеющему силу доступному источнику данных. Если это свойство установлено, оно автоматически модифицирует подробный набор данных для макроса $WHERE, когда происходят изменения в наборе данных.

Свойство MacrosEnabled

Применимо к TMySQLDataset

Определение

property MacrosEnabled : boolean;

Описание



Если установлено в True, допускает использование макрокоманд в Ваших инструкциях SQL.

Свойство MultiKeyFields

Применимо к TMySQLDataset

Определение

property MultiKeyFields : string;

Описание



Список строк всех полей, которые являются частью ключа, доступного в текущем (актуальном) наборе результатов. Только Run-time. Read-only.

Свойство MySQLFields

Применимо к TMySQLDataset

Определение

property MySQLFields : TStringList;

Описание



Список строк всех полей, используемых в текущем наборе результатов. Только Run-time. Read-only.

Свойство MySQLRecords

Применимо к TMySQLDataset

Определение

property MySQLRecords : TList;

Описание



Необработанные записи из текущего (актуального) набора результатов. Только Run-time. Read-only.

Свойство MySQLTables

Применимо к TMySQLDataset

Определение

property MySQLTables : TStringList;

Описание



Список всех таблиц, используемых в текущем наборе результатов. Только Run-time. Read-only.

Свойство PrimaryKeyFields

Применимо к TMySQLDataset

Определение

property PrimaryKeyFields : string;

Описание



Строковый список всех полей первичных ключей, доступных в текущем наборе результатов. Только Run-time. Read-only.

Свойство ReadOnly

Применимо к TMySQLDataset

Определение

property ReadOnly : boolean;

Описание



Изменение этого свойства включит или отключит редактирование текущего наборе результатов.

Свойство RealSQL

Применимо к TMySQLDataset



Определение

property RealSQL : string;

Описание



Последняя полная инструкция SQL, которая будет послана серверу MySQL. Только Run-time. Read-only.

Свойство Records

Применимо к TMySQLDataset

Определение

property Records[Index : Integer] : PRecInfo;

Описание



Необработанные записи текущего набора результатов. Только Run-time. Read-only.

Свойство Server

Применимо к MySQLDataset

Определение

property Server : TMySQLServer;

Описание



TMySQLServer, используемый этим набором данных.

Свойство ShareConnection

Применимо к TMySQLDataset

Определение

property ShareConnection : boolean;

Описание



Если True, этот набор данных совместно использует поточное подключение, обеспеченное TMySQLServer с TMySQLServer.

Обратите внимание: Соблюдайте осторожность при использовании этого, так как каждый набор данных может использовать любую базу данных, но разделяемое подключение может использовать в один момент времени только единственную базу данных. Если выставить значение в False, этот набор данных будет иметь собственное поточное подключение к серверу MySQL, организованное TMySQLServer. Все операции будут локальными и не смогут влиять на другой экземпляр TMySQLDataset или TMySQLServer.

Свойство SQL

Применимо к TMySQLDataset

Определение

property SQL : TStrings;

Описание



Тип SELECT SQL-запроса. Эти инструкции будут выполнены, каждый раз, когда Вы выполняете операцию Open или Active на наборе данных. Этот набор строк может содержать несколько инструкций, разделеных точкой с запятой (;). Последняя инструкция должна будет произвести набор результатов.

Свойство SQLBatch

Применимо к TMySQLDataset

Определение

property SQLBatch : TStrings;

Описание



Общая команда SQL. Эти инструкции будут выполнены каждый раз, когда Вы выполняете ExecBatch на наборе данных. Этот список строк может содержать несколько инструкций, разделеных точкой с запятой (;).

Свойство SQLDelete

Применимо к TMySQLDataset

Определение

property SQLDelete : TStrings;

Описание



DELETE-тип SQL-команды. Эти инструкции будут выполнены каждый раз, когда Вы выполняете Delete на наборе данных. Этот список строк может содержать несколько инструкций, разделеных точкой с запятой (;).



Свойство SQLInsert

Применимо к TMySQLDataset

Определение

property SQLInsert : TStrings;

Описание



INSERT-тип SQL-команды. Эти инструкции будут выполнены каждый раз, когда Вы выполняете Insert или Append на наборе данных. Этот список строк может содержать несколько инструкций, разделеных точкой с запятой (;).

Свойство SQLUpdate

Применимо к TMySQLDataset

Определение

property SQLUpdate : TStrings;

Описание



UPDATE-тип SQL-команды. Эти инструкции будут выполнены каждый раз, когда Вы выполняете Edit и Post на наборе данных. Этот список строк может содержать несколько инструкций, разделеных точкой с запятой (;).

Свойство TableName

Применимо к TMySQLDataset

Определение

property TableName : string;

Описание



Имя в настоящее время выбранной таблицы. Это заменит макросы $TABLENAME в Ваших инструкциях SQL.

Свойство UniqueKeyFields

Применимо к TMySQLDataset

Определение

property UniqueKeyFields : string;

Описание



Список всех уникальных полей, используемых в текущем наборе результатов. Только Run-time. Read-only.

Метод EscapeStr

Применимо к TMySQLDataset

Определение

function EscapeStr(const Value : string) : string;

Описание



Создает экранированную строку для сервера MySQL, используя функцию mysql_escape_string.

Метод ExecBatch

Применимо к TMySQLDataset

Определение

function ExecBatch : boolean;

Описание



Выполняет инструкции SQLBatch, использующие подключение набора данных и текущие параметры настройки.

Метод ExecSQL

Применимо к TMySQLDataset

Определение

function ExecSQL(SQL : string; EnableMacros, Cached : boolean) : boolean;

Описание



Выполнит любую инструкцию SQL, использующую подключение набора данных. Если EnableMacros равно True, SQL будет анализироваться, используя макрокоманды. Если Cached равно True, SQL-запрос будет послан серверу со следующим обращением к методу Close или Refresh.

Метод ExecSQLBatch

Применимо к TMySQLDataset

Определение

function ExecSQLBatch(SQL : TStrings; EnableMacros, Cached, AutoRefresh : boolean): boolean;

Описание





Выполнит любую инструкцию SQL, использующую подключение набора данных. Если EnableMacros равно True, SQL будет анализироваться, используя макрокоманды. Если Cached равно True, SQL-запрос будет послан серверу со следующим обращением к методу Close или Refresh. AutoRefresh не используется.

Метод GetMacroValue

Применимо к TMySQLDataset

Определение

function GetMacroValue(Name : string) : string;

Описание



Возвратит текущее значение макрокоманды Name как строку.

Метод HexStr

Применимо к TMySQLDatasetCVYCG0

Определение

function HexStr(S : PChar; L : longint) : string;

Описание



Применяется для полей типов BLOB и MEMO. Двоичные данные, указанные в S с длиной L возвратятся как строка, наподобие "0x623E63F...".

Метод LocateRecord

Применимо к TMySQLDataset

Определение

function LocateRecord(const KeyFields : string; const KeyValues : Variant; Options : TLocateOptions; SyncCursor : Boolean): Boolean;

Описание



Стандартный метод реализации Locate.

Метод LocateRecordOption

Применимо к TMySQLDatasetCVYCG0

Определение

function LocateRecordOption(const KeyFields : string; const KeyValues : Variant; Options : TLocateOptions; SyncCursor : Boolean; MySQLOptions : TMySQLLocateOptions; var MatchedField : TField) : Boolean;

Описание



Расширенная версия Locate. Это учитывает полный текстовый поиск на всех полях текущего набора результатов. Параметры KeyFields, KeyValues и Options работают так же, как и со стандартным методом Delphi Locate. Если SyncCursor равно True, набор данных будет установлен в первую согласованную запись. MySQLOptions определяет направление и тип поиска. MatchedField возвращает компонент TField, который соответствует критериям. Эта функция вернет True, если соответствие было найдено.

Метод MacroByName

Применим к TMySQLDataset.

Определение

function MacroByName(const Value : string) : TParam;

Описание



Дает Вам доступ во время выполнения ко всем макрокомандам, используемым в любых инструкциях SQL. TMySQLDataset может применяться без того, чтобы использовать любую макрокоманду.





Макросы



Макросы дают возможность Вам что-то задать в Вашем SQL-запросе однажды, а затем факультативно устанавливать части инструкций SQL позже.

Рассмотрим такую SQL-команду:

"select * from |$TABLENAME |JOIN |WHERE |GROUPBY |ORDER |LIMIT;"

Эта инструкция имеет 6 определенных макрокоманд, первая специальна, но посмотрим на макрос |WHERE.

По умолчанию это будет пустая строка, если не задано иное. Но если Вы факультативно хотите устанавливать это, Вы можете:

A) Используя Object Inspector:

Выбрать макрос, нажать на WHERE и ввести значение, подобно "WHERE AccountID=1".

Теперь закройте и снова откройте набор данных, текст будет помещен в Вашу инструкцию SQL и послан на сервер без того, чтобы заменить SQL-свойство.

B) В коде указать:

MySQLDataset1.MacroByName('WHERE').AsString := 'WHERE AccountID=1';

MySQLDataset1.Open;

В обоих случаях заключительная инструкция SQL, посланная серверу, будет выглядеть следующим образом:

"select * from Accounts WHERE AccountID=1;"

Вы можете устанавливать макрокоманды, даже если Ваш набор данных открыт. Они будут использоваться только, если инструкция SQL должна анализироваться и выполняться снова.

ОБРАТИТЕ ВНИМАНИЕ: Макрокоманды чувствительны к регистру!

Имеются несколько специальных макрокоманд, которые являются доступными для использования, но если Вы устанавливаете значение для них, это не будет иметь эффекта для результата заключительной инструкции SQL, поскольку все эти макрокоманды автоматически модифицируются и устанавливаются во время выполнения. Все они начинаются со знака $:

$RELOAD

Вызовет перезагрузку набора данных MySQLServer, результат этой макрокоманды: пустая строка.

$DATABASENAME

Будет заменен свойством DatabaseName Вашего MySQLDataset.

$TABLENAME

Будет заменен свойством TableName Вашего MySQLDatasset.

$FIELDNAME

Будет заменен первым полем в свойстве FieldName Вашего MySQLDataset. Разделитель ";" или ",".

$FIELDS

Будет заменен постоянными полями набора данных (поля, которые Вы определили двойным нажатием на Ваш набор данных). Если таких полей нет, макрос будет заменен на * (звездочку).



$WHERE

Будет заменен комбинацией свойств MasterFields и Filter. Например, если MasterFields установлен в "AccountID=AccountID" и Filter равен "AccountName like "J%", то результатом будет WHERE (AccountID=1) and (AccountName like "J%").

$MODIFIED$FIELDS&VALUES

Будет заменен изменяемыми полями текущей записи, результат примерно таков:

FieldName1="Value1",FieldName2="Value2",...

Обратите внимание: значения экранируются, пустые поля будут равны NULL, типы BLOB будут равняться 0x874365837546.

$UNMODIFIED$FIELDS&VALUES

Будет заменен неизменяемыми полями текущей записи, результат примерно таков: FieldName1="Value1",FieldName2="Value2",....

$MODIFIED$FIELD$NAMES

Будет заменен именами изменяемых полей текущей записи, результат примерно таков: FieldName1,FieldName2,....

$UNMODIFIED$FIELD$NAMES

Будет заменен именами неизменяемых полей текущей записи, результат примерно таков: FieldName1,FieldName2,....

$MODIFIED$FIELD$VALUES

Будет заменен значениями изменяемых полей текущей записи, результат примерно таков: "FieldValue1","FieldValue2",....

$UNMODIFIED$FIELD$VALUES

Будет заменен значениями неизменяемых полей текущей записи, результат примерно таков: "FieldValue1","FieldValue2",....

$OLD$FIELDS&VALUES

Будет заменен всеми полями в текущем наборе результатов и значениями для предыдущих значений текущей записи, результат напомнит: (FieldName1="Value1") and (FieldName2="Value2") and ....

$FIELDNAMES&VALUES

Будет заменен всеми свойствами FieldName (разделенными ";" или ","), именами полей и значениями для текущей записи, результат напомнит: (FieldName1="Value1") and (FieldName2="Value2") and ....

$PRIMARYFIELDS&VALUES

Будет заменен всеми полями первичного ключа в текущем наборе результатов и значениями для текущей записи, результат примерно такой: (FieldName1="Value1") and (FieldName2="Value2") and ....



ОБРАТИТЕ ВНИМАНИЕ: Если не имеется никаких полей первичного ключа в текущем результате, эта макрокоманда возвратит поля и значения для макроса $OLD$FIELDS&VALUES.

$UNIQUEFIELDS&VALUES

Будет заменен всеми уникальными полями в текущем наборе результатов и значениями для текущей записи, результат примерно такой: (FieldName1="Value1") and (FieldName2="Value2") and ....

$MULTIFIELDS&VALUES

Будет заменен всеми полями, которые являются частями составного ключа в текущем наборе результатов и значениями для текущей записи, результат будет примерно таким: (FieldName1="Value1") and (FieldName2="Value2") and ... .

$FIELDNAMES&VALUES$COMMA

Будет заменен всеми именами полей из свойства FieldName (разделенными ; или ,) и значениями для текущей записи: FieldName1="Value1",FieldName2="Value2",....

$FIELDNAME$VALUE

Будет заменен первым полем в свойстве FieldName текущей записи MySQLDataset: "FieldValue1".

YourFieldNameHere

Будет заменен полем, имя которого определено значением текущей записи. Регистр не имеет значения: "FieldValue1".

$OLD$YourFieldNameHere

Будет заменен полем, имя которого определено предыдущим значением текущей записи. Регистр не имеет значения: "FieldOldValue1".

Например, если Вы должны модифицировать запись в наборе результатов: update mytable set AccountName="abc" where AccountName="cba", Вы изменяете свойство SQL на update mytable set AccountName=|AccountName where AccountName=|$OLD$AccountName.

$PROMPT$Caption$PromptName$DefaultValue$PasswordChar

Запросит Вашего конечного пользователя на предмет значения, которое будет вставлено в sql-запрос. Параметры:

Caption: факультативный заголовок для диалога

PromptName: факультативное имя запрашиваемого значения

DefaultValue: факультативное значение по умолчанию

PasswordChar: факультативный парольный символ, например, *

Если макрокоманды не соответствуют никакому из этих специальных имен, то Macro.AsString используется, чтобы заменить макрокоманду в SQL, например: MySQLDataset1.MacroByName('WHERE').AsString := 'WHERE AccountID=1'; MySQLDataset1.Open;



Следующее предстваляет собой пример инструкций SQL из фактических программ:

SQL Property: Select

select * from |$TABLENAME WHERE AccountType LIKE "%Employee%"

SQLInsert Property: Insert

use MYSQL; insert into USER set host="%",user=|ACCOUNTNAME, password=PASSWORD(|$PROMPT$Password$$*), select_priv="Y",insert_priv="Y",update_priv="Y", delete_priv="Y", reload_priv="Y"; use |$DATABASENAME; insert into |$TABLENAME set |$MODIFIED$FIELDS&VALUES; |$RELOAD;

SQLUpdate Property: Update

use MYSQL; update user set user=|ACCOUNTNAME where user=|$OLD$ACCOUNTNAME; use |$DATABASENAME; update |$TABLENAME set |$MODIFIED$FIELDS&VALUES where |$FIELDNAME=|$FIELDNAME$VALUE; |$RELOAD;

SQLDelete Property: Delete

use MYSQL; delete from user where user=|ACCOUNTNAME; use |$DATABASENAME; delete from |$TABLENAME where |$FIELDNAME=|$FIELDNAME$VALUE; |$RELOAD;

Cascading deletes made easy:

delete from |$TABLENAME where |$FIELDNAMES&VALUES; //Master table

delete from devices where |$FIELDNAMES&VALUES; // Detail table

Метод ParseSQL

Применим к TMySQLDataset

Определение

function ParseSQL(SQL : string) : string;

Описание



Анализирует строку SQL, извлекает и добавлет все найденные макрокоманды.

Метод QuoteStr

Применим к TMySQLDataset

Определение

function QuoteStr(const S : string) : string;

Описание



Создает цитированную строку, например, "string" превратится в "`string`".

Метод ClearMacros

Применим к TMySQLDataset



Определение

procedure ClearMacros;

Описание



Очищает все установленные значения для существующих макрокоманд.

Метод ConnectEvent

Применим к TMySQLDataset

Определение

procedure ConnectEvent(Sender : TObject; Connecting : Boolean);

Описание



Позволяет набору данных знать то, что делает TMySQLServer. Это обычно используется только внутреннее между набором данных и TMySQLServer.

Событие OnExecSQL

Применимо к TMySQLDataset

Определение

property OnExecSQL : TMySQLEvent;



Описание



Это событие происходит только прежде, чем инструкция SQL будет послана серверу MySQL. SQL содержит полный SQL-запрос, который, возможно, изменен или продолжен, в зависимости от того, была ли эта инструкция выполнена или нет. Удобно для отладки.

Тип TMySQLEvent

Модуль MySQLDataset

Определение

type TMySQLEvent = procedure(Server: TMySQLDataset; var SQL: string; var Continue: boolean); of object;

Описание



Это событие происходит только прежде, чем инструкция SQL будет послана серверу MySQL. SQL содержит полный SQL-запрос, который, возможно, изменен или продолжен, в зависимости от того, была ли эта инструкция выполнена или нет. Удобно для отладки.

Тип TMySQLLocateOptions

Модуль MySQLDataset

Определение

type TMySQLLocateOptions = set of (loFirst, loNext, loPrior, loLast, loTextSearch, loMatchAll);

Описание



loFirst: вызывает First на наборе данных перед стартом поиска.

loNext: использует Next на наборе данных, чтобы искать вперед.

loPrior: использует Prior на наборе данных, чтобы искать назад.

loLast: вызывает Last на наборе данных перед стартом поиска.

loTextSearch: выполняет текстовый поиск на полях, включенных в search, таким образом, KeyValues должен содержать строку.

loMatchAll: все поля записи должны содержать значение, определенное для поиска в KeyValues.

Пример: свойства сервера

ShowMessage('MySQL server''s properties are:'#13#10+ 'Server version:'+MySQLServer1.ServerVersion+#13#10+ 'Client version:'+MySQLServer1.ClientVersion+#13#10+ 'Protocol:'+MySQLServer1.Protocol+#13#10+ 'Information:'+MySQLServer1.Info+#13#10+ 'Major:'+IntToStr(MySQLServer1.Major)+#13#10+ 'Minor:'+IntToStr(MySQLServer1.Minor)+#13#10+ 'Build:'+IntToStr(MySQLServer1.Build)+#13#10+ 'Complete:'+IntToStr(MySQLServer1.IntVer)+#13#10);

Пример: создание сервера

with TMySQLServer.Create(nil) do try Host := 'localhost'; Username := 'root'; Password := ''; DatabaseName := 'mysql'; LoginPrompt := False; Connected := True; ExecSQL('GRANT SELECT, INSERT, UPDATE, DELETE, RELOAD ON *.* TO 'Admin'@'%''); Reload; CreateDatabase('Test'); DropDatabase('Test'); GetDatabaseNames(List); GetTableNames('mysql',List); GetFieldNames('mysql','user',List); finally Free; end;



Пример: использование MySQLDataset

with TMySQLDataset.Create(nil) do try Server := MySQLServer1; DatabaseName := 'mysql'; TableName := 'user'; Active := True; ExecSQL(' GRANT SELECT, INSERT, UPDATE, DELETE, RELOAD ON *.* TO ''Admin''@''%''', True, False); Server.Reload; MacroByName('WHERE').AsString := 'where user=''root'''; Close; Open; ShareConnection := False; Open; // Now the dataset has it's own threaded connection ShareConnection := True; Open; // Now we are back on the TMySQLServer connection ClearMacros; MacroByName('ORDER').AsString := 'order by user'; MacroByName('LIMIT').AsString := 'limit 0,10'; Close; Open; CahcedUpdates := True; // All edits, insert, deletes, updates are now cached Edit; FieldByName('user').AsString := 'test'; Post; Close; // Cached statements flushed CachedUpdates := False; // Statements not cached, sent real-time to server finally Free; end;

              


Модуль MySQLServer


Этот модуль включает объект TMySQLServer, полученный из стандартного класса Delphi 5 TCustomConnection.

Компонент: TMySQLServer

Типы: TMySQLServerLoginEvent

Подпрограммы: MYSQLError

Описание

TMySQLServer представляет собой основной компонент в наборе TMySQLComponent. TMySQLServer используется, чтобы обработать фактические подключения к серверу MySQL, используя стандартные функции из libmysql.dll. Большую часть времени Вы будете использовать только один компонент сервера, зато много компонентов TMySQLDatasets.

Важно обратить внимание на то, что есть только одно физическое подключение к серверу MySQL. Все наборы данных, приложенные к этому TMySQLServer, используют это подключение или породят собственные подключения, использующие те же самые параметры настройки TMySQLServer.

Помимо этих функций, этот компонент имеет много полезных свойств и функций, чтобы создавать, удалять, использовать базы данных, получать информацию о версии, собирать списки баз данных, таблиц, полей и т. д.

Свойства

AfterConnect!AL("AfterConnect_Property") AfterDisconnect!AL("AfterDisconnect_Property") BeforeConnect!AL("BeforeConnect_Property") BeforeDisconnect!AL("BeforeDisconnect_Property") Build ClientVersion Compression Connected!AL("Connected_Property") DatabaseName Host IdleTimer Info IntVer LoginPrompt Major Minor Params Password Port Protocol ServerVersion UserName

Методы

Create!AL("Create_Method") Destroy!AL("Destroy_Method") AllocConnection ExecSQL FormatIdentifier FormatIdentifiers SelectDatabase Server CreateDatabase DropDatabase FreeConnection GetDatabaseNames GetFieldNames GetTableNames RegisterClient!AL("RegisterClient_Method") Reload SendEvent UnRegisterClient!AL("UnRegisterClient_Method")

События

Key events OnIdleTimer OnLogin

Цель

Обеспечить все приложенные наборы данных физическими подключениями к серверу MySQL, используя стандартную библиотеку libmysql.dll. Это основной компонент в наборе TMySQLComponent.


Свойство Build

Применимо к TMySQLServer

Определение

property Build : word;

Описание



Сервер формирует версию как слово, например, 32

Read-only

Свойство ClientVersion

Применимо к TMySQLServer

Определение

property ClientVersion : string;

Описание



Используемая версия клиентской разделяемой библиотеки libmysql.dll.

Read-only

Свойство Compression

Применимо к TMySQLServer

Определение

property Compression : boolean;

Описание



Определяет протокол сжатия, используемый при связи с сервером MySQL.

Свойство DatabaseName

Применимо к TMySQLServer

Определение

property DatabaseName : string;

Описание



Получает или определяет текущую (актуальную) базу данных для этого подключения.

Свойство Host

Применимо к TMySQLServer

Определение

property Host : string;

Описание



Получает или определяет имя хоста, используемое при создании новых подключений.

Свойство IdleTimer

Применимо к TMySQLServer

Определение

property IdleTimer : longword;

Описание



Получает или определяет актуальное время неактивности (тайм-аут), позволенное для этого подключения. Подключение автоматически будет пересоздано после того, как это время закончится, а связь еще нужна.

Свойство Info

Применимо к TMySQLServer

Определение

property Info : string;

Описание



Более подробная информация о сервере.

Read-only

Свойство IntVer

Применимо к TMySQLServer

Определение

property IntVer : longword;

Описание



Версия сервера как слово, например, 32306.

Read-only

Свойство LoginPrompt

Применимо к TMySQLServer

Определение

property LoginPrompt;

Описание



Если установлено в True, это учитывает настроенный диалог подсказки MySQL входа в систему, который будет появляться каждый раз, когда устанавливается связь с этим сервером.

Свойство Major

Применимо к TMySQLServer

Определение

property Major : word;

Описание



Старшая часть версии сервера как слово, например, 3

Read-only

Свойство Minor

Применимо к TMySQLServer

Определение

property Minor : word;

Описание



Младшая часть версии сервера как слово, например, 22



Read-only

Свойство Params

Применимо к TMySQLServer

Определение

property Params : TStrings;

Описание



Стандартные параметры, используемые для сервера событием OnLogin. Могут быть изменены во время выполнения.

Свойство Password

Применимо к TMySQLServer

Определение

property Password : string;

Описание



Получает или определяет текущий пароль, используемый при создании нового подключения.

Свойство Port

Применимо к TMySQLServer

Определение

property Port : word;

Описание



Получает или определяет текущий порт, используемый при связи с сервером.

Свойство Protocol

Применимо к TMySQLServer

Определение

property Protocol : string;

Описание



Используемый протокол связи: TCP/IP, Pipes и т.д.

Read-only

Свойство ServerVersion

Применимо к TMySQLServer

Определение

property ServerVersion : string;

Описание



Версия сервера MySQL в виде строки.

Read-only

Свойство UserName

Применимо к TMySQLServer

Определение

property UserName : string;

Описание



Получает или определяет текущее имя пользователя, используемое при создании нового подключения.

Метод AllocConnection

Применим к TMySQLServer

Определение

function AllocConnection : PMYSQL;

Описание



Распределяет новое подключение для TMySQLServer и TMySQLDatasets, используя текущие параметры настройки Username, Password, Port и прочие.

Это внутренне используемый метод, обычно он используется только порожденными классами TMySQLServer.

Метод ExecSQL

Применим к TMySQLServer

Определение

function ExecSQL(SQL : string) : boolean;

Описание



Используя подключение, выполнит любую инструкцию SQL на сервере.

Метод FormatIdentifier

Применим к TMySQLServer

Определение

function FormatIdentifier(Value : string) : string;

Описание



Форматирует идентификатор Value, используя информацию о версии сервера. Например, "Table 1" превратится в "`Table 1`".

Метод FormatIdentifiers

Применим к TMySQLServer

Определение

function FormatIdentifiers(const Value : string) : string;

Описание



Форматирует идентификаторы, полученные в строке Value, используя информацию о версии сервера. Например, "Table 1#10#13Table2#10#13Table 3" превратится в "`Table 1`,Table 2,`Table 3`".



Метод SelectDatabase

Применим к TMySQLServer

Определение

function SelectDatabase(Conn : PMYSQL; DB : string) : boolean;

Описание



Для данного подключения выбирает текущую (актуальную) базу данных, то есть действует аналогично команде "USE Database;". Это внутренне используемый метод. Обычно он применяется только классами, порожденными от TMySQLServer.

Метод Server

Применим к TMySQLServer

Определение

function Server : PMYSQL;

Описание



Представляет собой указатель на текущее потоковое подключение к серверу. Это может использоваться со всеми стандартными функциями mysql_, найденными в библиотеке libmysql.dll. Это внутренне используемый метод. Обычно он применяется только классами, порожденными от TMySQLServer.

Метод CreateDatabase

Применим к TMySQLServer

Определение

procedure CreateDatabase(Value : string);

Описание



При использовании подключения к серверу создает новую базу данных, то есть работает аналогично инструкции "CREATE Database;".

Метод DropDatabase

Применим к TMySQLServer

Определение

procedure DropDatabase(Value : string);

Описание



При использовании текущего подключения к серверу удаляет указанную базу данных, то есть работает аналогично инструкции "DROP Database;".

Метод FreeConnection

Применим к TMySQLServer

Определение

procedure FreeConnection(var Value : PMYSQL);

Описание



Освобождает активное подключение.

Метод GetDatabaseNames

Применим к TMySQLServer

Определение

procedure GetDatabaseNames(List : TStrings);

Описание



Заполняет список со всеми именами баз данных, найденными на сервере. Замечание: в этом списке не будут перечислены те базы данных, на которых Вы не имеете никаких привилегий.

Метод GetFieldNames

Применим к TMySQLServer

Определение

procedure GetFieldNames(const DatabaseName, TableName : string; List : TStrings);

Описание

Заполняет cписок всеми именами полей для таблицы TableName из базы данных DatabaseName с сервера.

Метод GetTableNames

Применим к TMySQLServer

Определение

procedure GetTableNames(const DatabaseName : string; List : TStrings);



Описание



Заполняет cписок всеми именами таблиц из базы данных DatabaseName.

Метод Reload

Применим к TMySQLServer

Определение

procedure Reload;

Описание



Перезагружает права доступа на сервере, то есть работает как команда "RELOAD;"

Метод SendEvent

Применим к TMySQLServer

Определение

procedure SendEvent(Connecting : Boolean);

Описание



Используется, чтобы разъединить все наборы данных, если сервер завершается. Это внутренне используемый метод. Обычно он применяется только классами, порожденными от TMySQLServer.

Событие OnIdleTimer

Применимо к TMySQLServer

Определение

property OnIdleTimer : TNotifyEvent;

Описание



Это событие происходит, когда заканчивается время ожидания подключения.

Событие OnLogin

Применимо к TMySQLServer

Определение

property OnLogin : TMySQLServerLoginEvent;

Описание



Это событие происходит прежде, чем подключение будет сделано, чтобы позволить Вам изменять свойства Params.

Тип TMySQLServerLoginEvent

Модуль MySQLServer

Определение

type TMySQLServerLoginEvent = procedure(Server : TMySQLServer; LoginParams : TStrings); of object;

Описание



Это событие происходит до установки связи с сервером MySQL. Список строк LoginParams в настоящее время поддерживает только два ключевых слова в форме: USERNAME=root, PASSWORD=.

Процедура MYSQLError

Модуль MySQLServer

Определение

procedure MYSQLError(MySQLHandle : PMySQL=nil; ErrNo : integer=-1; Msg : string=''; IntVer : longword=32100);

Описание



Универсальная функция создания исключительной ситуации, предоставляет зависящую от версии информацию относительно последней ошибки MySQL.


Использование модуля MySQL


import MySQL DBH = MySQL.connect() # localhost print DBH.listdbs() DBH.selectdb('test') print DBH.serverinfo() print DBH.stat() DBH["create table pytest (x int, y int, s char(20))"] DBH["insert into pytest values (1,2,'abc')"] DBH.do("insert into pytest values (3,4,'def')") STH = DBH.query("insert into pytest values (5,6,'ghi')") print STH.affectedrows() print DBH['select * from pytest'] STH = DBH.query("select * from pytest") print STH.numrows() print STH.fields() print STH.fetchrows(-1) STH.seek(0) print STH.fetchrows(1) print STH.fetchrows(1) STH.seek(0) print STH.fetchrows(2) print STH.fetchrows(2) print STH.numfields() STH.seek(0) print STH.fetchdict(1) print STH.fetchdict() STH = DBH.query("select * from pytest",1) print STH.fetchdict(1) print STH.fetchdict() # compare to previous dicts STH = DBH.query("select * from pytest",1) print STH.fetchrows(1) print STH.eof() print STH.fetchrows() print STH.eof() DBH['drop table pytest']



Экспортируемые типы, функции и классы


Модуль MySQL экспортирует следующее:

DBH_Type:
Тип объекта базы данных. STH_Type:
Тип ошибки объекта курсора (исключительная ситуация, выдаваемая в некоторых обстоятельствах вместо TypeError). __doc__:
Версия, доступная из Python connect([host[,user[,pass]]])
Функциональный возврат объекта базы данных. Факультативные параметры: имя компьютера (host), с которым надлежит соединиться, username для связи с MySQL и соответствуюющий пароль password. Если никакой компьютер не задан, функция примет localhost (и будет использовать Unix-сокет для подключения к нему). escape(string)
Вернет правильно экранированную строку, чтобы позволить вставку в DB. Эта подпрограмма вызывает mysql_escape_string(), которая в 3.21.29-gamma не работает. Версия 3.21.30 и выше работают нормально.

Обратите внимание: в следующем "таблица" означает "список списков" (за исключением fetchdict). MySQL.connect() вернет дескриптор базы данных (DBH) со следующими методами:

Table = DBH.listdbs([wild])
Возвращает таблицу, дающую имена баз данных на компьютере MySQL, с которым соединился через вызов MySQL.connect(). Факультативный параметр: MySQL-строка с символами подстановки (синтаксис аналогичен LIKE). DBH.selectdb(DB_Name[,storage])
Присоединяет этот объект к специфической базе данных. Выполненные запросы будут направлены к этой базе данных, пока не будет сделано другое обращение метода selectdb. Факультативный параметр storage типа integer может использоваться, чтобы хранить наборы результатов запросов на сервере. Обратите внимание, что это отрицательно воздействует на эффективность сервера, но позволяет клиентуре с маленькой памятью работать с записями по мере надобности. Значение по умолчанию: 0, то есть все записи перемещены пользователю сразу. Table = DBH.listtables([wild])
Возвращает таблицу с именами таблиц в выбранной базе данных. Имеет силу только после того, как было сделано обращение selectdb. Факультативный параметр может использоваться, чтобы ограничить возвращенный набор таблиц (тот же самый синтаксис, какой принят в LIKE). Table = DBH.listfields(table[,wild])
Возвращает таблицу описаний полей в данной таблице. Факультативный параметр может использоваться, чтобы ограничить возвращенный набор полей (тот же самый синтаксис, какой принят в LIKE). Table = DBH.listprocesses()
Возвращает информацию относительно работающих процессов MySQL. Требует соответствующих привилегий (иначе возвращает None). String = DBH.stat()
Возвращает информацию состояния из MySQL. DBH.create(DB_Definition)
Создает новую базу данных.


DBH.drop(DB_Name)
Удаляет базу данных. DBH.reload()
Перезагружает таблицы привилегий MySQL. DBH.shutdown()
Завершает сервер MySQL. DBH.close()
Закрывает DB-подключение. String = DBH.clientinfo()
Возвращает информацию о версии MySQLmodule. String = DBH.serverinfo()
Возвращает информацию о сервере MySQL.

String = DBH.hostinfo()
Возвращает информацию относительно хоста соединения и типа подключения. Integer = DBH.protoinfo()
Возвращает информацию о версии протокола MySQL. Table = DBH.do(query) или Table = DBH[query]
Возвращает результат запроса SQL или число обработанных строк. Оба метода используют тип памяти, установленный в DBH.selectdb(). Integer = DBH.insert_id()
Предоставляет доступ к последнему сгенерированному числу auto_increment. Это число может изменяться, если были запросы между обращениями. STH = DBH.query(query[,storage])
Возвращает операторный дескриптор для методов курсора (см. ниже). Факультативный параметр storage может использоваться, чтобы отменить значение по умолчанию DBH, установленное DBH.selectdb().

Методы для операторных дескрипторов (STH):

Table = STH.fetchrows([n])
Возвращает результаты запроса к DB. Если n<0, все строки будут выбраны. Иначе будут возвращены только следующие n строк. Значение по умолчанию должно возвратить все строки. Table = STH.fetchdict([n])
Аналогично STH.fetchrows(), за исключением того, что список словарей возвращен с парами tablename.fieldname:data. Table = STH.fields()
Возвращает описания поля результата запроса STH. В настоящее время MySQLmodule понимает "pri", "notnull", "auto_inc", "ukey" и "mkey" . STH.seek(n)
Двигает курсор к строке n (0 определяет первую строку). Доступен только, если результат хранится на стороне пользователя (выбрано в DBH.selectdb). Иначе создает исключительную ситуацию. Integer = STH.numrows()
Возвращает, сколько строк находятся в результате запроса STH. Предупреждение: в действительности это число отражает сколько записей получил клиент. Для методов хранения на стороне сервера, это начинается с 0 и увеличивается по мере того, как пользователь выбирает строки. Для методов хранения на стороне клиента это число немедленно дает общее количество строк для этого запроса. Integer = STH.numfields()
Возвращает, сколько столбцов находятся в результате запроса STH. Integer = STH.affectedrows()
Возвращает данные на сколько строк воздействовал последний запрос. Обратите внимание, что MySQL не всегда возвращает правильное значение. Integer = STH.insert_id()
Возвращает значение auto_increment из STH-запроса insert. Обратите внимание, что это число постоянно, пока STH существует. Integer = STH.eof()
Возвратит 1, если последняя строка читалась, иначе 0. Всегда 1, если выбрано хранение данных на стороне пользователя (значение по умолчанию).


Компиляция и установка модуля MySQL


Скопируйте MySQLmodule.c в подкаталог Modules дерева исходников Python. Добавьте следующие строки в Ваш файл Setup в этом каталоге: MySQL MySQLmodule.c -L/usr/local/lib/mysql/ -lmysqlclient \ -I/usr/local/include/mysql

Обратите внимание, что расположение библиотеки MySQL и include-каталога может быть иным на Вашей специфической системе. Вы можете формировать разделяемый модуль (вставкой ниже индикатора shared в файле Setup).

Если Вы формировали Python ранее, просто выполните make в Вашем основном каталоге Python. Если нет, следуйте командам о том, как компилировать и установить Python.

Чтобы формировать динамически загружаемый модуль без доступа к дереву исходников python, используйте: gcc -shared -I/usr/include/python1.5 -I/usr/local/include/mysql \ MySQLmodule.c -lmysqlclient -L/usr/lib/python1.5/config \ -lpython1.5 -o MySQLmodule.so

Переместите возникающий в результате файл MySQLmodule.so в PYTHONPATH. Замените соответствующие расположения Ваших библиотек и include-файлов.

Обратите внимание, что модуль чувствителен к регистру, и что имя было изменено на MySQL, чтобы не разорвать любой существующий код, который использует старый модуль mySQL.



Этот модуль был разработан под


Этот модуль был разработан под Linux (RH50), MySQL 3.21.30 и Python 1.5.1. MySQLmodule-1.x основан на mySQLmodule-0.1.4, разработанном:

Copyright (C) 1997 Joseph Skinner Copyright (C) 1997 James Henstridge

mySQLmodule-0.1.4 в свою очередь основан на mSQLmodule, разработанном:

Portions copyright (C) 1995 Thawte Consulting, cc Portions copyright (C) 1994 Anthony Baxter


Почему другой интерфейс Python/MySQL?


Была обнаружена проблема при сохранении строк, содержащих ASCII-ноль (\0) в базе данных MySQL. После расследования в языке Python (который создал первоначальную ошибку), был проверен код mySQLmodule и там найден ряд проблем. Некоторые подпрограммы не освобождают распределенную память, некоторые функции MySQL API не были доступны, и многих разработчиков совершенно не устраивал тот факт, что mySQLmodule возвратит различные структуры данных в зависимости от метода. Так что я переделал код. Так как эти изменения включают изменение в методах Python и значениях возврата, был повышен код версии и изменено имя модуля на MySQL, чтобы оно не столкнулось с оригиналом (mySQL).

Рационально возвратить список списков вместо набора или списка наборов. Не стоит создавать ситуацию, когда подпрограммы доступа к DB занимаются обработкой типа возврата, и стоит предусмотреть возможность изменить данные в возвращенной таблице напрямую. Data = DBH['select * from MyTable'] if Data: rows = len(Data) cols = len(Data[0]) for i in range(rows): for j in range(cols): if not Data[i][j]: Data[i][j] = DefaultElement() Do_Something(Data)

Никакой потребности усложнять это при наличии наборов внутри внешнего списка нет. Для тех, кто предпочитает словари, метод STH fetchdict() возвратит список словарей. Ключи словаря квалифицированы с соответствующим именем (возможно, не одним) обрабатываемой таблицы.



Примечания относительно хранения на сервере


MySQL предлагает два немного различных пути доступа к данным из базы данных.

Заданный по умолчанию метод в MySQLmodule состоит в том, чтобы использовать хранение на стороне пользователя, то есть все запросы, включая методы курсора (STH), выбирают все данные с сервера. К строкам обращаются через STH.fetchrows(n) или STH.fetchdict(n) индивидуально (n=1), блочно (n>1), все строки забирают одной порцией (n<0) или не обращаются вообще (n=0). STH.numrows() может сообщать после запроса сколько строк находится в результате. STH.seek(k) может использоваться, чтобы обратиться к строкам в произвольном порядке. Недостаток хранения на стороне пользователя состоит в том, что это использует память пользователя, чтобы сохранить все строки. Этот способ учитывает конструкции типа: STH = DBH.query("select * from Foo") N = STH.numrows() if N > 1000: raise Hell,"You must be joking!" for i in xrange(N): [Data] = STH.fetchdict(1)

Так как пользователь действительно переместил к себе все строки, которые подготовил сервер, все транзакции на этом канале прекратились, и сервер готов принять новые команды. Это также означает, что STH.eof() всегда true (1) для хранения данных на стороне клиента.

Хранение на стороне сервера не требует, чтобы у пользователя было много памяти. Все записи будут перемещены на основании запроса. Однако, этот способ имеет несколько недостатков. Так как теперь возникает возможность того, что пользователь не забрал все строки, каждая новая команда должна проверить, является ли свободным, то есть готов ли он принять новую команду. Если нет, команда должна очистить канал команды, выдавая запросы на чтение в количестве, достаточном, чтобы получить оставшиеся строки. MySQL API 3.21 не предлагает команды abort(). STH.numrows() не знает ничего относительно того, сколько строк были выбраны запросом, так что вышеупомянутый код примера будет падать. STH.numrows() будет, однако, модифицироваться, поскольку строки все-таки читаются, например: STH = DBH.query("select * from Foo") Data = STH.fetchrows(-1) print "Got",STH.numrows(),"rows." # len(Data) is the same


STH.eof() имеет смысл только при хранении данных на сервере, но даже здесь такой код полезен не всегда: STH = DBH.query("select 1") print STH.eof() # will print 0 Data = STH.fetchrows(1) # retrieve the row print STH.eof() # still 0 :-( Data = STH.fetchrows(1) # must repeat. Data will be [] print STH.eof() # now we get 1, but we already # knew that we've hit the end
Можно было рассматривать это, как ошибку. STH.seek(k) больше не доступен и создает исключение ("cannot seek on server"), то есть строки должны теперь читаться последовательно.
Хранение на стороне сервера также создает дополнительную нагрузку на сервер. В частности, он должен остаться в контакте с пользователем, пока все строки не будут прочитаны. Так что лучше бы быстро получить все строки и не делать длинную обработку или, что еще хуже, позволять пользователю останавливать поиск (например, нажимая клавиши Ctrl-S в интерактивном интерфейсе).
Для тех, кто не может решить, который метод является более подходящим для прикладной программы, MySQLmodule позволяет смешивать оба метода свободно. Заданное по умолчанию поведение может быть установлено через DBH.selectdb() и может быть изменено для индивидуального курсора (STH). Обратите внимание, что незавершенные запросы будут отменены последующими командами: STH = DBH.query("select * from Foo",1) # use server side storage Tables = DBH.listtables() # stomp on previous results Data = STH.fetchrows() # nothing here anymore vs. STH = DBH.query("select * from Foo",0) # use client side storage Tables = DBH.listtables() # won't interfere Data = STH.fetchrows() # no problem...
Хранение на стороне сервера также создает более сложный код в MySQLmodule. Обычно при хранении на стороне клиента STH-курсоры независимы от дескриптора базы данных. Немедленно после запроса все данные будут перекачаны клиенту, и пользователь может делать все, что сочтет необходимым с дескриптором DBH. Но при хранении на стороне сервера это становится сложным. С курсорами стороны сервера указатель на дескриптор сохранен в дескрипторе STH. MySQLmodule удостоверится, что этот кусок памяти не освобожден прежде, чем закроются все ожидающие обработки курсоры. Это означает, что mysql_close() не обязательно вызван, если база данных, обрабатываемая DBH, разрушена: DBH = MySQL.connect() # get a DB handle STH = DBH.query("select 1",1) # server side cursor del DBH # mysql_close() *not* called STH.fetchrows() # will succeed! del STH # now mysql_close() will be called # in DBH_dealloc()
Если Вы должны закрыть дескриптор DB немедленно, используйте DBH.close(). Все дальнейшие попытки работать на этом дескрипторе (даже ожидающие обработки курсоры стороны сервера) получат исключительную ситуацию "... server has gone away". Начиная с того момента, как mySQL не может принимать команды из последовательности, все DBH-методы должны проверить незавершенные STH-курсоры. Чтобы обращаться к ним, дескриптор DBH хранит указатель на STH-курсор.

Установка MySQLmodule-1.4 под Windows NT


Следующие инструкции основаны на информации, предоставленной Nigel Head (nhead@houbits.com).

Вы должны получить файл libMySQL.dll из клиентского пакета win32-mysql версии 3.22.8 или выше, более ранние версии не будут работать. Это доступно на www.tcx.se (или зеркалах) для свободной загрузки. Вы должны, вероятно, переместить файл в то же самое расположение, что и Ваша библиотека python15.dll. Скомпилируйте MySQLmodule-1.4 с включенным переключателем WIN32. VC5 и файлы проекта MySQL.dsp и MySQL.dsw включены (но, вероятно, их придется изменять, чтобы удовлетворить требованиям Вашей среды). Переместите возникающий в результате файл MySQL.pyd в Ваш каталог Python DLL.

Если что-то пойдет не так, помощь лучше всего поискать в конференции comp.lang.python.

              



How to Apply These Terms to Your New Libraries


If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).

To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found. one line to give the library's name and an idea of what it does.

Copyright (C) year name of author

This library 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.

This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker.

signature of Ty Coon, 1 April 1990 Ty Coon, President of Vice

That's all there is to it!

       



How to Apply These Terms to Your New Programs


If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found.

one line to give the program's name and a brief idea of what it does.

Copyright (C) yyyy name of author

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

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

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

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author

Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.

The hypothetical commands show w and show c should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than show w and show c; they could even be mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.

signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.

              



Как сообщать об ошибках и сбоях


Написание хорошего отчета об ошибке требует немало терпения, но при выполнении этого экономится много времени Вам и всем окружающим. Хороший отчет об ошибке, содержащий полный случай теста для ошибки, делает весьма вероятным скорейшее исправление проблемы. Этот раздел поможет Вам написать Ваш отчет так, чтобы Вы не тратили впустую Ваше время, выполняя действия, которые не могут ничем помочь.

Пользуйтесь скриптом mysqlbug, чтобы генерировать отчет об ошибке (или отчет относительно любой проблемы), если возможно. Сам mysqlbug может быть найден в каталоге scripts в дистрибутиве исходного кода или (для двоичного дистрибутива) в каталоге bin под Вашим каталогом установки MySQL. Если Вы не можете использовать mysqlbug, Вы должны все же включать всю необходимую информацию, перечисленную в этом разделе.

Скрипт mysqlbug помогает Вам сгенерировать отчет, определяя многое из следующей информации автоматически, но если кое-что важное отсутствует, пожалуйста, включите это в Ваше сообщение! Пожалуйста, читайте этот раздел тщательно и удостоверьтесь, что вся информация, описанная здесь, включена в Ваш отчет.

Нормальное место, чтобы сообщить ошибки и проблемы: mysql@lists.mysql.com. Если Вы можете создать случай теста, который ясно показывает ошибку, Вы должны его послать на . Обратите внимание, что в этом списке Вы должны только регистрировать полный повторимый отчет ошибки, использующий скрипт mysqlbug. Если Вы работаете под Windows, Вы должны включить описание операционной системы и версии MySQL. Предпочтительно, Вы должны проверить проблему при использовании последнего устойчивого дистрибутива или версии для разработчика. Любой должен быть способен повторить ошибку, используя только mysql test<script на включенном случае теста или выполнить скрипт, который включен в отчет ошибки. Все ошибки, зарегистрированные в списке bugs, будут исправлены или зарегистрированы в следующем выпуске MySQL! Если имеются только маленькие изменения кода, в этом списке может быть опубликован патч.


Не забудьте, что можно ответить на сообщение, содержащее слишком много информации, но не на то, в котором полезных данных очень мало. Часто люди опускают факты потому, что они думают, что они знают причину проблемы и считают, что некоторые важнейшие детали не имеют значения. Хороший принцип: если Вы находитесь в сомнении относительно установления чего-либо, устанавливайте это! Это намного ускорит и упростит работу всем остальным.

Наиболее общие ошибки состоят в том, что люди не указывают номер версии MySQL или ОС (включая ее версию!), на которой работают. Это очень важная информация, и в 99 случаях из 100 отчет об ошибке без нее бесполезен! Часто спрашивают об ошибках, которые есть в старых версиях, но их уже нет в новых. Обновляйте софт, меньше будет проблем! Иногда ошибка платформно-зависимая, в таких ситуациях почти невозможно установить что-нибудь без того, чтобы знать операционную систему и номер версии платформы.

Не забудьте также обеспечивать информацию относительно Вашего компилятора, если это связано с проблемой. Часто люди находят ошибки в компиляторах и считают, что это проблемы MySQL. Большинство компиляторов вечно находятся в состоянии разработки и совершенствования. Чтобы определить, зависит или нет Ваша проблема от компилятора, авторы должны знать, какой именно компилятор используется. Обратите внимание, что каждая проблема компиляции должна быть расценена как отчет об ошибке и сообщена соответственно.

Самые лучшие отчеты такие, которые включают полный пример, показывающий как воспроизвести ошибку или проблему.

Если программа производит сообщение об ошибках, очень важно включить сообщение в Ваш отчет! Если мы пробуем искать данные из архива, используя сведения по этой программе лучше, чтобы присланное сообщение об ошибках точно соответствовало тому, которое программа производит. Вы никогда не должны пробовать запомнить то, что было в сообщении об ошибке, вместо этого скопируйте и вставьте сообщение в Ваш отчет!

Пожалуйста, не забудьте, что многие из тех, кто будет читать Ваш отчет, применяют монитор в режиме с 80 символами в строке. Следовательно, при изготовлении отчетов и примеров с использованием клиента mysql Вы должны использовать опцию --vertical (или завершать команду комбинацией символов \G) для вывода, который не превысит доступную ширину для такого дисплея (например, инструкция EXPLAIN SELECT, подробности ниже).



Пожалуйста, включите следующую информацию в Ваш отчет:

Версия дистрибутива MySQL (например, MySQL Version 3.22.22). Вы можете выяснить, которой версией пользуетесь, командой mysqladmin version. mysqladmin может быть найден в каталоге bin под каталогом установок MySQL. Изготовитель и модель машины, на которой Вы работаете. Имя операционной системы и версия. Для большинства операционных систем, Вы можете получить эту информацию, выполняя Unix-команду uname -a. Иногда объем памяти (реальной и виртуальной) релевантен. Если сомневаетесь, включите эти значения. Если Вы используете исходники MySQL, нужны имя и версия компилятора. Если Вы имеете двоичный дистрибутив, необходимо его имя. Если проблема происходит в течение трансляции, включите точное сообщение об ошибках, а также несколько строк контекста кода из файла, где ошибка произошла. Если mysqld рухнул, Вы должны также сообщить запрос, который потерпел крах. Вы можете обычно найти его, запуская mysqld с включеным протоколированием. Если любая таблица базы данных связана с проблемой, включите вывод из mysqldump --no-data db_name tbl_name1 tbl_name2 .... Это очень простой и мощный способ получить информацию относительно любой таблицы в базе данных, которая поможет создать ситуацию, соответствующую той, что у Вас. Для связанных с быстродействием ошибок или проблем с инструкциями SELECT Вы должны всегда включать вывод EXPLAIN SELECT ... и по крайней мере число строк, которые производит инструкция SELECT. Большее количество информации, которую Вы даете относительно Вашей ситуации, делает более вероятным, что кто-то сможет помочь Вам! Например, следующее представляет собой пример очень хорошо составленного отчета об ошибке (это должно быть, конечно, создано с помощью скрипта mysqlbug). Обратите внимание на использование признака конца оператора \G для инструкций, чья ширина вывода иначе превысила бы 80 символов: mysql> SHOW VARIABLES; mysql> SHOW COLUMNS FROM ...\G < Вывод SHOW COLUMNS> mysql> EXPLAIN SELECT ...\G < Вывод EXPLAIN> mysql> FLUSH STATUS; mysql> SELECT ...; < Короткая версия вывода из SELECT, включая время, затраченное на обработку запроса> mysql> SHOW STATUS; < Вывод SHOW STATUS>



Если ошибка или проблема происходит при работе mysqld, попробуйте сделать скрипт, который воспроизведет аномалию. Этот скрипт должен включить любые необходимые исходные файлы. Если у Вас получается сделать такой пример, который точно воспроизводит ошибку при минимальных усилиях со стороны изучающего, направьте его на bugs@lists.mysql.com для приоритетной обработки ситуации! Если Вы не можете обеспечить готовый скрипт, Вы должны по крайней мере включить вывод mysqladmin variables extended-status processlist, чтобы обеспечить некоторую информацию о раболте Вашей системы. Если Вы не можете изготовить случай теста в нескольких строках, или если таблица теста слишком большая, чтобы быть отправленной по почте в список рассылки (больше, чем 10 строк), Вы должны сделать дамп Вашей таблицы, используя mysqldump, и создать файл README, который описывает Вашу проблему. Создайте сжатый архив Ваших файлов, используя tar и gzip (или zip), и передайте его по ftp на ftp://support.mysql.com/pub/mysql/secret. Затем пошлите короткое описание проблемы на bugs@lists.mysql.com. Если Вы думаете, что MySQL производит странный результат, включите не только сам результат, но также и Ваше мнение, каким он должен быть, а также основание для Вашего мнения. При предоставлении примера проблемы, лучше использовать имена переменных, таблицы и т.д., которые существуют в Вашей фактической ситуации, чем придумывать новые. Проблема может быть связана с именем переменной или таблицы. Эти случаи редки, возможно, но лучше подстраховаться. В конце концов это должно быть проще для Вас, чтобы обеспечить пример, который использует Вашу фактическую ситуацию. В случае если Вы имеете данные, которые Вы не хотите показывать другим, Вы можете передать их по ftp на ftp://support.mysql.com/pub/mysql/secret. Если данные совершенно секретны, используйте другие имена, но это крайние меры. Включите все параметры, данные релевантным программам, если возможно. Например, укажите параметры, которые Вы используете, когда запускаете mysqld, и что Вы используете, чтобы выполнить любые программы клиента MySQL. Параметры к программам mysqld и mysql, а также скрипту configure, часто являются ключами к решениям и очень нужны. Во всяком случае включить их не помешает. Если Вы используете любые модули, типа Perl или PHP, пожалуйста, включите также номера их версий. Если Ваш вопрос связан с системой привилегии, пожалуйста, включите вывод mysqlaccess, mysqladmin reload и все сообщения об ошибках, которые Вы получили при попытке подключить! Когда Вы проверяете Ваши привилегии, Вы должны сначала выполнить mysqlaccess. После этого выполните mysqladmin reload version и попробуйте соединиться с программой, которая создает проблему. Команда mysqlaccess есть в каталоге bin под каталогом установки MySQL. Если Вы имеете заплату для ошибки, которая является хорошей, пришлите ее авторам в комплекте со случаем теста, иллюстрирующим применение заплаты. Помните, что без детального описания и тестового примера, разработчики могут и не понять назначение заплатки, а следовательно, и не будут ее применять. Покажите, что заплата обработает все ситуации, которые могут возникнуть. Присылайте предположения касательно причин ошибки. Без таких предположений сложно с первой попытки понять, какой именно кусок кода надо отлаживать и изучать. К тому же, описание причин упрощает отладку. Если Вы получаете ошибку синтаксического анализа (parse error), пожалуйста, проверьте Ваш синтаксис очень тщательно! Если Вы не можете найти что-то неправильное в нем, чрезвычайно вероятно, что Ваша текущая версия MySQL просто не поддерживает запрос, который Вы используете. Если Вы применяете самую свежую версию, и руководство на http://www.mysql.com/documentation/manual.php не покрывает синтаксис, который Вы применили, значит MySQL не поддерживает Ваш запрос. Если руководство покрывает синтаксис, который Вы используете, но Вы имеете старую версию MySQL, Вы должны проверить хронологию изменения MySQL, чтобы увидеть, когда синтаксис был реализован. В этом случае следует обновить версию. Если проблема разрушает данные в таблицах, или Вы получаете ошибки, когда обращаетесь к некоторой специфической таблице, Вы должны сначала проверить и пробовать восстановить Ваши таблицы с помощью myisamchk или CHECK TABLE и REPAIR TABLE. Если Вы часто получаете разрушенные таблицы, Вы должны пробовать выяснить, когда и почему это случается! В этом случае файл mysql-data-directory/'hostname'.err может содержать некоторую информацию относительно того, что случалось. Пожалуйста, включите любую релевантную информацию из этого файла в Ваш отчет об ошибке. Как правило, mysqld никогда не должен разрушить таблицу, если ничто не уничтожило его посреди модификации. Если Вы можете найти причину слета mysqld, это сильно облегчит работу. Если возможно, загрузите и поставьте самую современную версию MySQL и проверьте, не решило ли это проблему. Все версии MySQL полностью проверены и должны бы работать без проблем! В пакете поддерживается обратная совместимость, так что переход на новую версию займет несколько минут.

Направьте отчет на адрес соответствующей рассылки. Может кто-то еще испытал (и возможно решил) такую проблему. Если Вы подписаны на поддержку, пишите на mysql-support@mysql.com.

Когда ответы посланы Вам индивидуально, а не списку рассылки, считается хорошим тоном суммировать ответы и послать резюме в список рассылки, чтобы все могли с ним ознакомиться и решить свои проблемы.


Preamble


The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.


To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.

Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.

Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.

When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.

We call this license the Lesser General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.

For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.

In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.

Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.

The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a ``work based on the library'' and a ``work that uses the library''. The former contains code derived from the library, whereas the latter must be combined with the library in order to run.


Переменные окружения


Имеется список всех системных переменных, которые используются MySQL непосредственно или косвенно. Большинство их также может быть найдено в других местах в этом руководстве.

Обратите внимание, что любые параметры в командной строке будут иметь приоритет над значениями, определенными в файлах конфигурации и системных переменных, а значения в файлах конфигурации всегда имеют приоритет над значениями в системных переменных.

DBI_USER Заданный по умолчанию пользователь для интерфейса Perl DBI.
DBI_TRACE Используется при трассировке Perl DBI.
HOME Заданный по умолчанию путь для файла хронологии mysql, обычно $HOME/.mysql_history.
LD_RUN_PATH Используется, чтобы определить, где находится Ваша библиотека libmysqlclient.so.
MYSQL_DEBUG Опции трассировки при отладке.
MYSQL_HISTFILE Путь к файлу хронологии mysql.
MYSQL_HOST Заданное по умолчанию имя хоста, используемое подсказкой командной строки mysql.
MYSQL_PWD Заданный по умолчанию пароль при соединении с mysqld. Обратите внимание, что использование этой возможности задания пароля опасно!
MYSQL_TCP_PORT Заданный по умолчанию порт TCP/IP.
MYSQL_UNIX_PORT Сокет по умолчанию. Используется для связи с localhost.
PATH Используется оболочкой для поиска программ и утилит пакета MySQL.
TMPDIR Каталог, где будут созданы временные таблицы или файлы.
TZ Это должно быть установлено к Вашей зоне местного времени.
UMASK_DIR Создание каталога пользователя будет выполнено с данной маской прав доступа. Обратите внимание, что это значение будет использовано в операции AND с UMASK!
UMASK То же самое, но для создания файлов.
USER Заданный по умолчанию пользователь в Windows, чтобы использовать при соединении с mysqld.

              



Выяснение вопросов или сообщение об ошибках в пакете


Перед отправкой отчета об ошибке или вопроса сделайте следующее:

Начните с поисков в руководстве по MySQL. Самая свежая версия (увы, только на английском языке) есть по адресу:
http://www.mysql.com/documentation/manual.php

Ищите также в архиве списков рассылки по MySQL:
http://www.mysql.com/documentation

Вы можете также использовать http://www.mysql.com/search.html для поиска по всем страницам на http://www.mysql.com/.

Если Вы не можете найти ответ в руководстве или архиве, проконсультируйтесь с Вашим локальным экспертом MySQL. Если Вы все еще не можете найти ответ на Ваш вопрос, читайте следующий раздел относительно того, как послать запрос на mysql@lists.mysql.com.



GNU GENERAL PUBLIC LICENSE


Version 2, June 1991

Copyright © 1989, 1991 Free Software Foundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.



GNU LESSER GENERAL PUBLIC LICENSE


Version 2.1, February 1999

Copyright © 1991, 1999 Free Software Foundation, Inc. 59 Temple Place -- Suite 330, Boston, MA 02111-1307, USA

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.]



Руководящие принципы ответов на вопросы в списках рассылки


Если Вы полагаете, что Ваш ответ представляет широкий интерес, Вы можете отправить его в список рассылки вместо того, чтобы ответить лично индивидууму, который Вас спросил. Пожалуйста, удостоверьтесь, что Ваш ответ не дублирует другой.

Попробуйте суммировать существенную часть вопроса в Вашем ответе, не надо цитировать все первоначальное сообщение. Пожалуйста, не отправляйте сообщения почты из Вашего браузера с включенным режимом HTML! Много пользователей не читают почту в браузере.

              



TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION


This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The ``Program'', below, refers to any such program or work, and a ``work based on the Program'' means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) Each licensee is addressed as ``you''. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:


This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called ``this License''). Each licensee is addressed as ``you''. A ``library'' means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The ``Library'', below, refers to any such software library or work which has been distributed under these terms. A ``work based on the Library'' means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) ``Source code'' for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:




Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.



9.4 NO WARRANTY

BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.



The modified work must itself be a software library. You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a ``work that uses the Library''. Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a ``work that uses the Library'' with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a ``work that uses the library''. The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a ``work that uses the Library'' uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. As an exception to the Sections above, you may also combine or link a ``work that uses the Library'' with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:



Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable ``work that uses the Library'', as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. Verify that the user has already received a copy of these materials or that you have already sent this user a copy.For an executable, the required form of the ``work that uses the Library'' must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:



Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.

You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.



9.6 NO WARRANTY

BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.