issue55:tutopython
Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
issue55:tutopython [2012/01/21 19:37] – fredphil91 | issue55:tutopython [2012/01/30 21:50] (Version actuelle) – fredphil91 | ||
---|---|---|---|
Ligne 5: | Ligne 5: | ||
Let's start by looking at the MySQL dump file. It consists of a section that creates the database, and then sections that create each table within the database followed by the data for that table, if it's included in the dump file. (There' | Let's start by looking at the MySQL dump file. It consists of a section that creates the database, and then sections that create each table within the database followed by the data for that table, if it's included in the dump file. (There' | ||
- | Il y a quelques | + | Il y a quelque |
- | Le programme MySQL Administrator vous permet de sauvegarder une base de données dans un fichier texte à plat. Beaucoup de navigateurs SQLite vous permettent de lire un fichier SQL de définition à plat et de créer la base de données à partir de là. Cependant, il y a beaucoup de choses que MySQL supporte mais pas SQLite. Alors ce mois-ci, nous allons écrire un programme de conversion qui lit un fichier de « dump » (sauvegarde) MySQL et crée une version SQLite. | + | Le programme MySQL Administrator vous permet de sauvegarder une base de données dans un fichier texte à plat. Beaucoup de navigateurs SQLite vous permettent de lire un fichier SQL de définition à plat et de créer la base de données à partir de là. Cependant, il y a beaucoup de choses que MySQL supporte, mais pas SQLite. Alors ce mois-ci, nous allons écrire un programme de conversion qui lit un fichier de « dump » (sauvegarde) MySQL et crée une version SQLite. |
- | Commençons par regarder le fichier de « dump » MySQL. Il se compose d'une section qui crée la base de données, puis des sections qui créent chaque table dans la base et insèrent des données dans ces tables, si les données sont contenues dans le fichier de « dump ». (Il existe une option pour exporter seulement les schémas des tables). Ci-dessus à droite se trouve un exemple d'une des sections de création de table. | + | Commençons par regarder le fichier de « dump » MySQL. Il se compose d'une section qui crée la base de données, puis des sections qui créent chaque table dans la base et insèrent des données dans ces tables, si les données sont contenues dans le fichier de « dump ». (Il existe une option pour exporter seulement les schémas des tables.) Ci-dessus à droite se trouve un exemple d'une des sections de création de table. |
**The first thing that we would need to get rid of is in the last line. Everything after the ending parenthesis needs to go away. (SQLite does not support an InnoDB database). In addition to that, SQLite doesn' | **The first thing that we would need to get rid of is in the last line. Everything after the ending parenthesis needs to go away. (SQLite does not support an InnoDB database). In addition to that, SQLite doesn' | ||
Ligne 21: | Ligne 21: | ||
Quant aux données, les déclarations « INSERT INTO » sont également non-compatibles. Le problème ici est que SQLite ne permet pas les insertions multiples dans une même déclaration. Voici un court exemple tiré du fichier de « dump » MySQL. Remarquez (à droite) que le marqueur de fin de ligne est un point-virgule. | Quant aux données, les déclarations « INSERT INTO » sont également non-compatibles. Le problème ici est que SQLite ne permet pas les insertions multiples dans une même déclaration. Voici un court exemple tiré du fichier de « dump » MySQL. Remarquez (à droite) que le marqueur de fin de ligne est un point-virgule. | ||
- | Nous allons également ignorer toutes les lignes de commentaires, et les instructions « CREATE DATABASE » et « USE ». Une fois que nous aurons le fichier SQL converti, nous utiliserons un programme semblable à SQLite Database Browser qui est dans le domaine | + | Nous allons également ignorer toutes les lignes de commentaires et les instructions « CREATE DATABASE » et « USE ». Une fois que nous aurons le fichier SQL converti, nous utiliserons un programme semblable à SQLite Database Browser qui est dans le domaine |
**Let' | **Let' | ||
Ligne 37: | Ligne 37: | ||
Commençons. Ouvrez un dossier pour ce nouveau projet et un nouveau fichier python. Nommez-le MonSQLversSQLite.py. | Commençons. Ouvrez un dossier pour ce nouveau projet et un nouveau fichier python. Nommez-le MonSQLversSQLite.py. | ||
- | Vous voyez ci-dessus à droite la déclaration d' | + | Vous voyez ci-dessus à droite la déclaration d' |
- | Ce programme sera exécuté en ligne de commande, nous avons donc besoin de créer la déclaration « if < | + | Ce programme sera exécuté en ligne de commande, nous avons donc besoin de créer la déclaration « if < |
def erreur(message): | def erreur(message): | ||
Ligne 54: | Ligne 54: | ||
where “Foo” is the name of the MySQL dump file, and “Bar” is the name of the SQLite sql file we want the program to create.** | where “Foo” is the name of the MySQL dump file, and “Bar” is the name of the SQLite sql file we want the program to create.** | ||
- | La routine FaitLe() est appelée si notre programme est lancé à partir de la ligne de commande, ce pour quoi il est conçu. Cependant, si nous voulons pouvoir en faire une bibliothèque qui sera incluse dans un autre programme à un autre moment, nous pouvons simplement utiliser la classe. Ici nous avons mis en place un certain nombre de variables pour s' | + | La routine FaitLe() est appelée si notre programme est lancé à partir de la ligne de commande, ce pourquoi |
- | Quand nous commençons le programme, nous devons fournir au moins deux variables sur la ligne de commande. Ce sont les fichiers d' | + | Quand nous commençons le programme, nous devons fournir au moins deux variables sur la ligne de commande. Ce sont les fichiers d' |
MonSQLversSQLite FicEntree=Foo FicSortie=Bar | MonSQLversSQLite FicEntree=Foo FicSortie=Bar | ||
Ligne 62: | Ligne 62: | ||
où « Foo » est le nom du fichier de dump MySQL, et « Bar » est le nom du fichier SQLite que le programme doit créer. | où « Foo » est le nom du fichier de dump MySQL, et « Bar » est le nom du fichier SQLite que le programme doit créer. | ||
- | You can also call it like this: | + | **You can also call it like this: |
MySQL2SQLite Infile=Foo Outfile=Bar Debug SchemaOnly | MySQL2SQLite Infile=Foo Outfile=Bar Debug SchemaOnly | ||
Ligne 70: | Ligne 70: | ||
Finally if the user asks for help, we just go to the usage portion of the program. | Finally if the user asks for help, we just go to the usage portion of the program. | ||
- | Before we continue, let's take another look at how the command line argument support works. | + | Before we continue, let's take another look at how the command line argument support works.** |
- | When a user enters the program name from the command line (terminal), the operating system keeps track of the information entered and passes it to the program just in case there are any options entered. If no options (also called arguments) are entered, the number of arguments is one, which is the name of the application - in our case MySQL2SQLite.py. We can access these arguments by calling the sys.arg command. If the count is greater than one, we will access them in a for loop. We will step through the list of arguments and check each one. Some programs require you to enter the arguments in a specific order. By using the for loop approach, the arguments can be entered in any order. If the user doesn't supply any arguments, or uses the help arguments, we show the usage screen. Shown above is the routine for that. | + | Vous pouvez également l'appeler ainsi : |
- | Moving on, once we have parsed the argument set, we instantiate the class, call the setup routine, which fills certain variables and then call the DoWork routine. We'll start our class now (which is shown on the next page, bottom right). | + | MonSQLversSQLite FicEntree=Foo FicSortie=Bar Debug SchemaSeulement |
- | This (next page, top right) is the definition and the __init__ routine. Here we setup the variables that we will need as we go through the code. Remember that right before we call the DoWork routine, we call the Setup routine. We take our empty variables and assign the correct values to them here. Notice that there is the ability to not write to a file, useful for debugging purposes. We also have the ability to simply write the schema, or database structure, without writing the data. This is helpful if you are taking a database and starting a new project without wanting to use any existing data. | + | ce qui ajoutera l' |
- | We start off by opening the SQL Dump file, then setting some internal scope variables. We also define some strings to save us typing later on. Then, if we are to write to an output file, we open it and then we start the entire process. We will read each line of the input file, process it, and potentially write it to the output file. We use a forced while loop to assist reading each line, with a break command when there is nothing left in the input file. We use f.readline() to get the line to work, and assign it to the variable “line”. Some lines, we can safely ignore. We'll simply use an if/elif statement followed by a pass statement to accomplish this (below). | + | Finalement si l' |
- | Next we can stop ignoring things and actually do something. If we have a CreateTable statement, we'll start that process. Remember we defined CT to be equal to “Create Table”. Here (above right), we set a variable “CreateTableMode” to be equal to 1, so we know that's what we are doing, since each field definition is on a separate line. We then take our line, remove the carriage return, and get that ready to write to our out file, and, if required, write it. | + | Avant de continuer, regardons à nouveau comment fonctionne la prise en charge des arguments de la ligne de commande. |
+ | |||
+ | **When a user enters the program name from the command line (terminal), the operating system keeps track of the information entered and passes it to the program just in case there are any options entered. If no options (also called arguments) are entered, the number of arguments is one, which is the name of the application - in our case MySQL2SQLite.py. We can access these arguments by calling the sys.arg command. If the count is greater than one, we will access them in a for loop. We will step through the list of arguments and check each one. Some programs require you to enter the arguments in a specific order. By using the for loop approach, the arguments can be entered in any order. If the user doesn' | ||
+ | |||
+ | Moving on, once we have parsed the argument set, we instantiate the class, call the setup routine, which fills certain variables and then call the DoWork routine. We'll start our class now (which is shown on the next page, bottom right).** | ||
+ | |||
+ | Lorsqu' | ||
+ | |||
+ | Ensuite, une fois que nous avons analysé l' | ||
+ | |||
+ | **This (next page, top right) is the definition and the < | ||
+ | |||
+ | We start off by opening the SQL Dump file, then setting some internal scope variables. We also define some strings to save us typing later on. Then, if we are to write to an output file, we open it and then we start the entire process. We will read each line of the input file, process it, and potentially write it to the output file. We use a forced while loop to assist reading each line, with a break command when there is nothing left in the input file. We use f.readline() to get the line to work, and assign it to the variable “line”. Some lines, we can safely ignore. We'll simply use an if/elif statement followed by a pass statement to accomplish this (below).** | ||
+ | |||
+ | Voici (page suivante, en haut à droite) les configurations et la routine < | ||
+ | |||
+ | Nous commençons par ouvrir le fichier de dump SQL, puis nous définissons les variables à portée interne. Nous définissons aussi certaines chaînes pour nous éviter de les saisir plus tard. Ensuite, si nous prévoyons d' | ||
+ | |||
+ | **Next we can stop ignoring things and actually do something. If we have a CreateTable statement, we'll start that process. Remember we defined CT to be equal to “Create Table”. Here (above right), we set a variable “CreateTableMode” to be equal to 1, so we know that's what we are doing, since each field definition is on a separate line. We then take our line, remove the carriage return, and get that ready to write to our out file, and, if required, write it. | ||
Now (middle right) we need to start dealing with each line within the create table statements - manipulating each line to keep SQLite happy. There are many things that SQLite won't deal with. Let's look at a Create Table statement from MySQL again. | Now (middle right) we need to start dealing with each line within the create table statements - manipulating each line to keep SQLite happy. There are many things that SQLite won't deal with. Let's look at a Create Table statement from MySQL again. | ||
- | One thing that SQLite will absolutely have an issue with is the entire last line after the closing parenthesis. Another is the line just above that, the Primary Key line. Yet another thing is the unsigned keyword in the second line. It will take a bit of code (below) to work around these issues, but we can make it happen. | + | One thing that SQLite will absolutely have an issue with is the entire last line after the closing parenthesis. Another is the line just above that, the Primary Key line. Yet another thing is the unsigned keyword in the second line. It will take a bit of code (below) to work around these issues, but we can make it happen.** |
+ | |||
+ | Ensuite nous pouvons cesser d' | ||
+ | |||
+ | Maintenant (à droite au milieu), nous devons commencer à traiter chaque ligne contenue dans l' | ||
+ | |||
+ | Une chose qui va vraiment poser problème à SQLite est la toute dernière ligne après la parenthèse fermante. Une autre est la ligne juste au-dessus, la ligne de clé primaire. Une autre chose est le mot-clé unsigned à la deuxième ligne. Cela va nécessiter un peu de code (ci-dessous) pour contourner ces problèmes, mais nous pouvons y arriver. | ||
- | First, (third down on the right) we check to see if the line contains “auto increment”. We will assume that this will be the primary key line. While this might be true 98.6% of the time, it won't always be. However, we'll keep it simple. Next we check to see if the line starts with “) ”. This will signify this is the last line of the create table section. If so, we simply set a string to close the statement properly in the variable “newline”, | + | **First, (third down on the right) we check to see if the line contains “auto increment”. We will assume that this will be the primary key line. While this might be true 98.6% of the time, it won't always be. However, we'll keep it simple. Next we check to see if the line starts with “) ”. This will signify this is the last line of the create table section. If so, we simply set a string to close the statement properly in the variable “newline”, |
Now (bottom right) we use the information we found about the auto increment key word. First, we strip the line of any spurious spaces, then check to see where (we are assuming it is there) the phrase “ int(“ is within the line. We will be replacing this with the phrase “ INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL”. The length of the integer doesn' | Now (bottom right) we use the information we found about the auto increment key word. First, we strip the line of any spurious spaces, then check to see where (we are assuming it is there) the phrase “ int(“ is within the line. We will be replacing this with the phrase “ INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL”. The length of the integer doesn' | ||
Ligne 94: | Ligne 118: | ||
elif line.strip().startswith(PK): | elif line.strip().startswith(PK): | ||
| | ||
- | pass | + | pass** |
- | Now (top right) we look for the phrase “ unsigned “ (again keep the extra spaces) and replace it with “ “. | + | Tout d' |
+ | |||
+ | Maintenant (en bas à droite), nous utilisons les informations que nous avons trouvées sur le mot-clé auto incrément. Tout d' | ||
+ | |||
+ | Maintenant nous cherchons l' | ||
+ | |||
+ | elif line.strip().startswith(PK): | ||
+ | pass | ||
+ | |||
+ | **Now (top right) we look for the phrase “ unsigned “ (again keep the extra spaces) and replace it with “ “. | ||
That's the end of the create table routine. Now (below) we move on to the insert statements for the data. The InsertStart variable is the phrase “INSERT INTO “. We check for that because MySQL allows for multiple insert statements in a single command, but SQLite does not. We need to make separate statements for each block of data. We set a variable called “insertmode” to 1, pull the “INSERT INTO {Table} {Fieldlist} VALUES (“ into a reusable variable (which I'll call our prelude), and move on. | That's the end of the create table routine. Now (below) we move on to the insert statements for the data. The InsertStart variable is the phrase “INSERT INTO “. We check for that because MySQL allows for multiple insert statements in a single command, but SQLite does not. We need to make separate statements for each block of data. We set a variable called “insertmode” to 1, pull the “INSERT INTO {Table} {Fieldlist} VALUES (“ into a reusable variable (which I'll call our prelude), and move on. | ||
Ligne 103: | Ligne 136: | ||
elif self.SchemaOnly == 0: | elif self.SchemaOnly == 0: | ||
- | if insertmode == 1: | + | if insertmode == 1:** |
- | We check to see if there is either “' | + | Maintenant (en haut à droite) nous recherchons l'expression « unsigned » (encore une fois remarquez les espaces supplémentaires) et la remplaçons par « ». |
- | posx = line.find("' | + | C'est la fin de la routine de création de table. Maintenant (ci-dessous), |
- | pos1 = line.find("' | + | |
- | l1 = line[:pos1] | + | Maintenant, nous vérifions si nous devons seulement travailler sur le schéma. Si oui, nous pouvons ignorer sans problème toutes les instructions d' |
+ | |||
+ | elif self.SchemaSeulement == 0: | ||
+ | if ModeInsertion == 1: | ||
+ | |||
+ | **We check to see if there is either “' | ||
+ | |||
+ | | ||
+ | pos1 = line.find("' | ||
+ | l1 = line[:pos1] | ||
This line checks for escaped single quotes and replaces them. | This line checks for escaped single quotes and replaces them. | ||
- | line = line.replace(" | + | |
If we have a closing statement (“);”), that is the end of our insert set, and we can create the statement by joining the prelude to the actual value statement. This is shown on the previous page, bottom right. | If we have a closing statement (“);”), that is the end of our insert set, and we can create the statement by joining the prelude to the actual value statement. This is shown on the previous page, bottom right. | ||
- | This all works (top right) if the last value we have in the insert statement is a quoted string. However, if the last value is a numeric value, we have to deal with things a bit differently. You'll be able to pick out what we are doing here. | + | This all works (top right) if the last value we have in the insert statement is a quoted string. However, if the last value is a numeric value, we have to deal with things a bit differently. You'll be able to pick out what we are doing here.** |
- | Finally, we close our input file, and, if we are writing an output file, we close that as well. | + | Nous vérifions s'il y a soit « '); » soit « '), » dans notre ligne. Le cas « '); » indique que c'est la dernière ligne de l' |
+ | |||
+ | posx = line.find ("' | ||
+ | pos1 = line.find ("' | ||
+ | longueur1 = ligne[: | ||
+ | |||
+ | Cette ligne vérifie s'il y a des apostrophes échappées et les remplace. | ||
+ | |||
+ | ligne = ligne.replace(" | ||
+ | |||
+ | Si nous avons une déclaration de clôture (" | ||
+ | |||
+ | Tout cela fonctionne (en haut à droite) si la dernière valeur que nous avons dans l' | ||
+ | |||
+ | **Finally, we close our input file, and, if we are writing an output file, we close that as well. | ||
f.close() | f.close() | ||
Ligne 131: | Ligne 187: | ||
As always, the code is up at PasteBin at http:// | As always, the code is up at PasteBin at http:// | ||
- | See you next time. | + | See you next time.** |
+ | |||
+ | Enfin, nous fermons notre fichier d' | ||
+ | |||
+ | f.close () | ||
+ | if self.EcrireFichier == 1: | ||
+ | FichierDest.close () | ||
+ | |||
+ | Une fois que vous avez votre fichier converti, vous pouvez utiliser SQLite Database Browser pour remplir la structure de la base et les données. | ||
+ | |||
+ | Ce code devrait fonctionner tel quel dans plus de 90 % des cas. Nous pourrions avoir oublié certaines choses à cause d' | ||
+ | |||
+ | Comme toujours, le code est disponible sur Pastebin : http:// | ||
+ | |||
+ | À la prochaine fois. |
issue55/tutopython.1327171021.txt.gz · Dernière modification : 2012/01/21 19:37 de fredphil91