Dopo gli accidenti tirati precedentemente, ho scoperto che dare un comando CHANGE su una colonna dichiarandola come TIMESTAMP ha il seguente effetto: il default diventa CURRENT_TIMESTAMP e l’extra è ON UPDATE CURRENT_TIMESTAMP.
Avevo letto che CHANGE e MODIFY cancellavano gli attributi (l’Extra) delle colonne cui cambiavano il tipo, e così mi sono messo ad assegnare TIMESTAMP e DATETIME ai due campi created/updated in modo da togliermi i dubbi.
(dal man: “When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.“)
sim:test> ALTER TABLE A CHANGE created created DATETIME; sim:test> ALTER TABLE A CHANGE updated updated TIMESTAMP; [...] | created | datetime | YES | | NULL | | | updated | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
Alla fine mi sono un po’ capito leggendo qua.
I dati di tipo timestamp dovrebbero essere dei datetime (e lo sono come formato), ma a differenza di questi ultimi si aggiornano con l’ora attuale.
The TIMESTAMP data type offers automatic initialization and updating.
Dopo aver reso la colonna updated CURRENT_TIMESTAMP con aggiornamento sull’UPDATE dei dati, ho potuto fare:
ALTER TABLE A MODIFY created TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00';
e inserire un paio di dati:
sim:test> INSERT INTO A (word) VALUES ('gastone');
sim:test> INSERT INTO A (word,created) VALUES ('paperino',NULL);
col risultato:
| 5 | gastone | 0000-00-00 00:00:00 | 2010-02-11 23:42:03 | | 6 | paperino | 2010-02-11 23:42:23 | 2010-02-11 23:42:23 |
Sul man c’è scritto pure questo, ma a me continua a sembrare un comportamento strano.
TIMESTAMP columns are NOT NULL by default, cannot contain NULL values, and assigning NULL assigns the current timestamp.
In conclusione, se volete avere dei campi con la creazione e l’aggiornamento automatico delle date incluso, leggetevi la pagina di Mysql sui timestamp.
Qua c’è da uscire di senno. A me MySQL sta pure simpatico, ma fa veramente di tutto per farmi sentire male.
Parto proprio dall’inizio.
sim:none> CREATE DATABASE test CHARACTER SET = 'UTF8'; Query OK, 1 row affected (0.00 sec) sim:none> CONNECT test; Connection id: 230 Current database: test
Ammettiamo che io voglia creare una tabella canonica con vari campi, fra cui l’id come PK, un campo per segnare quando il record è stato creato (created) ed uno per segnarmi quando è stato aggiornato l’ultima volta (updated).
sim:test> CREATE TABLE A (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
word VARCHAR(8) NOT NULL,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP NOT NULL );
Query OK, 0 rows affected (0.00 sec)
La situazione della mia tabella A per ora è chiara.
sim:test> SHOW CREATE TABLE A \G;
*************************** 1. row ***************************
Table: A
Create Table: CREATE TABLE `A` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`word` varchar(8) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
Inserisco anche un paio di record che appaiono come ci si aspetta:
sim:test> INSERT INTO A (word) VALUES ('pippo'),('pluto');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
sim:test> SELECT * FROM A;
+----+-------+---------------------+---------------------+
| id | word | created | updated |
+----+-------+---------------------+---------------------+
| 1 | pippo | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
| 2 | pluto | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
+----+-------+---------------------+---------------------+
2 rows in set (0.00 sec)
Nel caso si decida di aggiornare un record:
sim:test> UPDATE A SET word = 'topolino' WHERE id=2; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 sim:test> SELECT * FROM A; +----+----------+---------------------+---------------------+ | id | word | created | updated | +----+----------+---------------------+---------------------+ | 1 | pippo | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 | | 2 | topolino | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 | +----+----------+---------------------+---------------------+ 2 rows in set (0.00 sec)
A questo punto decido che questa disposizione dei dati non mi va più bene, che fare? Semplice (* le ultime parole famose TM ), leggo il manuale e sistemo. Seee…
Un po’ di pazzia MySQL:
sim:test> SHOW COLUMNS FROM A; +---------+------------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+------------------+------+-----+---------------------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | word | varchar(8) | NO | | NULL | | | created | timestamp | NO | | CURRENT_TIMESTAMP | | | updated | timestamp | NO | | 0000-00-00 00:00:00 | | +---------+------------------+------+-----+---------------------+----------------+ 4 rows in set (0.00 sec) sim:test> ALTER TABLE A ALTER created DROP DEFAULT; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 sim:test> SHOW COLUMNS FROM A; +---------+------------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+------------------+------+-----+---------------------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | word | varchar(8) | NO | | NULL | | | created | timestamp | NO | | NULL | | | updated | timestamp | NO | | 0000-00-00 00:00:00 | | +---------+------------------+------+-----+---------------------+----------------+ 4 rows in set (0.00 sec) sim:test> ALTER TABLE A CHANGE created creat TIMESTAMP; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 sim:test> SHOW COLUMNS FROM A; +---------+------------------+------+-----+---------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +---------+------------------+------+-----+---------------------+-----------------------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | word | varchar(8) | NO | | NULL | | | creat | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP | | updated | timestamp | NO | | 0000-00-00 00:00:00 | | +---------+------------------+------+-----+---------------------+-----------------------------+ 4 rows in set (0.00 sec)
Con un magico DROP del DEFAULT di un campo ed un cambio nome ottengo di nuovo il CURRENT_TIMESTAMP come default, e pure l’update automatico sul campo.
Provare per credere:
sim:test> INSERT INTO A (word) VALUES ('minnie');
Query OK, 1 row affected (0.00 sec)
sim:test> SELECT * FROM A;
+----+----------+---------------------+---------------------+
| id | word | creat | updated |
+----+----------+---------------------+---------------------+
| 1 | pippo | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
| 2 | topolino | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
| 3 | minnie | 2010-02-11 23:02:36 | 0000-00-00 00:00:00 |
+----+----------+---------------------+---------------------+
3 rows in set (0.00 sec)
sim:test> UPDATE A SET word = 'clarabella' WHERE id=3;
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 1
sim:test> SELECT * FROM A;
+----+----------+---------------------+---------------------+
| id | word | creat | updated |
+----+----------+---------------------+---------------------+
| 1 | pippo | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
| 2 | topolino | 2010-02-11 22:23:41 | 0000-00-00 00:00:00 |
| 3 | clarabel | 2010-02-11 23:03:35 | 0000-00-00 00:00:00 |
+----+----------+---------------------+---------------------+
3 rows in set (0.00 sec)
Robe da pazzi.
Note:
1) MySQL aggiunge alle funzionalità dell’SQL (che vorrebbe una sola query per riga) la possibilità di comandi multipli in un solo statement: ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;
Dovevo trasferire rapidamente i dati da una singola tabella in un db MySQL a quattro distinte – in modo da normalizzare un po’ i dati.
Con perl e DBI la cosa viene facile.
use strict;
use DBI;
[…]
my $dsn = "dbi:mysql:database=$db_name";
my $dbh = DBI->connect( $dsn, $username, $password ) or die $DBI::errstr;
my $sth = $dbh->prepare(
‘SELECT name, surname, birth, address, cap, city, country, phone, email, notes FROM rubrica’
) or die $dbh->errstr;
$sth->execute();
my $ins0 = $dbh->prepare(
‘INSERT INTO persone (nome,cognome) VALUES (?,?)’
) or die $dbh->errstr;
my $ins1 = $dbh->prepare(
‘INSERT INTO indirizzi (id,via,cap,citta,paese) VALUES (?,?,?,?,?)’
) or die $dbh->errstr;
[… ecc, seguono altri statement insert …]
while ( my $row = $sth->fetchrow_hashref() ) {
$ins0->execute( $row->{name}, $row->{surname} );
my $rv = $dbh->last_insert_id(undef, undef, ‘persone’, ‘id’);
$ins1->execute( $rv, $row->{address}, $row->{cap}, $row->{city}, $row->{country} );
[…]
}
La cosa interessante sta in quel last_insert_id che raccatta l’ultimo valore auto incrementato e lo mette in uno scalare, riutilizzabile poi in altri insert per avere le foreign key allineate.
Dopo qualche ripensamento, ho deciso di spostare alcuni campi che stavano in una tabella (in MySQL) in un’altra. Come fare in maniera automatica?
Se si vuole farlo solo per certe occorrenze, mettere un filtro WHERE in fondo per limitare gli update.
E se si vuole confrontare i dati e vedere se è tutto giusto?
Lo sapevo che prima o poi mi avrebbe punito.
Ho imparato l’SQL e i db stando su MySQL, poi sono passato a Pg per varie ragioni (di lavoro ed altro).
Mi sono trovato assolutamente bene con Postgre – pur lottando ogni tanto con la sua macchinosità, e alla fine mi sono ritrovato a non usare mai MySQL… fino ad oggi. E ovviamente non mi ricordo (quasi) più nulla.
Poco male, si ricomincia. E due DB is meil che one (almeno finchè ci sono gli ORM come DBIC che capiscon tutto loro).
Mentre pistolavo a casaccio, ho visto che MySQL ha un tot di script da shell che mostrano un po’ di robba, e comunque aiutano se li si impara ad usare.
$ mysqlshow +--------------------+ | Databases | +--------------------+ | information_schema | | agenda | | cmsfdt | | evento_odg | | libri | | mail | | mysql | | studiog7 | | system_backup | | test | | test_blog | | wines | | wp281 | +--------------------+ $ mysqlshow libri Database: libri +---------+ | Tables | +---------+ | book | | details | +---------+ $ mysqlshow libri book Database: libri Table: book +---------+-----------+-------------------+------+-- | Field | Type | Collation | Null | .. +---------+-----------+-------------------+------+-- | id | int(11) | | NO | .. | titolo | char(100) | latin1_swedish_ci | NO | .. | autore | char(100) | latin1_swedish_ci | NO | .. | editore | char(50) | latin1_swedish_ci | NO | .. +---------+-----------+-------------------+------+---
A me è parso caruccio.
Edit postumo: mysqlshow ha un po’ di opzioni. Una cosa che ho trovato utile è stato usare l’opzione –count che dice quante righe ha la tabella richiesta (ho aggiunto in ~/.bashrc alias mysqlshow=’mysqlshow –count’)
Funzionozze per interrogare MySQL con il C.
La lista completa delle funzioni sul sito di MySQL.
Prototipo di mysql_init(), per allocare memoria e inizializzare l’oggetto MYSQL.
proto: MYSQL *mysql_init(MYSQL *mysql)
Dopo aver inizializzato l’oggetto si puo’ creare la connessione al db con mysql_real_connect().
proto: MYSQL *mysql_real_connect(MYSQL *mysql, const char *host,
const char *user, const char *passwd, const char *db,
unsigned int port, const char *unix_socket, unsigned long client_flag)
Esempio: mysql_real_connect(&mysql, host, user, pass, db_name, 0, NULL, 0)
La query si chiama col prototipo che segue inserendo la stringa stmt_str e la lunghezza della stessa (es.: con strlen()). Se ritorna zero, la query è avvenuta.
proto: int mysql_real_query(MYSQL *mysql, const char *stmt_str,
unsigned long length)
L’analisi del risultato è un po’ macchinosa.
Il risultato della query viene incamerato grazie alla funzione mysql_store_result() che incamera i dati nella struct MYSQL_RES.
proto: MYSQL_RES *mysql_store_result(MYSQL *mysql)
Esempio:
MYSQL mysql; MYSQL_RES *result; [ blah blah blah... ] result = mysql_store_result(&mysql)
Notare che result rappresenta il risultato della query, sia esso
- Nullo perchè la query non è andata a buon fine
- Con dati causati da un SELECT o uno SHOW.
- Con risultato ma senza dati causato magari da un INSERT (che non spamma righe ma un risultato di righe modificate).
La struct MYSQL_RES di result puo’ venire esplorata con varie funzioni.
La funzione principale è probabilmente mysql_fetch_row(result) che estrae le singole righe dal result set.
proto: MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
Il numero di valori nella riga (i campi restituiti) è dato da mysql_num_fields(result) e mysql_num_rows() conta le righe restituite.
proto: unsigned int mysql_num_fields(MYSQL_RES *result) proto: my_ulonglong mysql_num_rows(MYSQL_RES *result)
Questo dovrebbe bastare per “navigare” i risultati della SELECT query (un bell’esempio per ciclare i risultati della query lo si trova in fondo alla pagina del fetch).
Per chiudere le operazioni, usare mysql_free_result(result) per liberare la memoria allocata per il result set e mysql_close(&mysql).
Aggiuntine.
mysql_fetch_result(result) parsa i campi.
proto: MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result)
num_fields = mysql_num_fields(result);
fields = mysql_fetch_fields(result);
for(i = 0; i < num_fields; i++)
{
printf("Field %u is %s\n", i, fields[i].name);
}
MySQL è the world’s most popular open source database.
C è un (il?) linguaggio di programmazione sviluppato da D. Ritchie per implementare Unix OS.
L’API è l’application programming interface.
Il file /usr/include/mysql/mysql.h è l’header che contiene classi, funzioni e variabili per mysql (#include <mysql/mysql.h>).
Il manualazzo delle API MySQL.
MYSQL è la struttura per maneggiare la connessione al database (le si associa una variabile, e ne si richiama l’indirizzo con l’operatore unario & ogni qual volta serva – cioè sempre).
typedef struct st_mysql
{
[... blah blah blah ...]
char *host,*user,*passwd,*unix_socket,*server_version,*host_info,*info;
char *db;
struct charset_info_st *charset;
MYSQL_FIELD *fields;
MEM_ROOT field_alloc;
my_ulonglong affected_rows;
[... blah blah blah ...]
my_bool free_me; /* If free in mysql_close */
my_bool reconnect; /* set to 1 if automatic reconnect */
/*
Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
from mysql_stmt_close if close had to cancel result set of this object.
*/
my_bool *unbuffered_fetch_owner;
[... blah blah blah ...]
} MYSQL;
MYSQL_RES è la struttura rappresentante il risutlato di una query che ritorna delle righe (es. SELECT).
typedef struct st_mysql_res {
my_ulonglong row_count;
MYSQL_FIELD *fields;
MYSQL_DATA *data;
MYSQL_ROWS *data_cursor;
unsigned long *lengths; /* column lengths of current row */
MYSQL *handle; /* for unbuffered reads */
MEM_ROOT field_alloc;
unsigned int field_count, current_field;
MYSQL_ROW row; /* If unbuffered read */
MYSQL_ROW current_row; /* buffer to current row */
my_bool eof; /* Used by mysql_fetch_row */
/* mysql_stmt_close() had to cancel this result */
my_bool unbuffered_fetch_cancelled;
const struct st_mysql_methods *methods;
} MYSQL_RES;
MYSQL_ROW è un array che rappresenta una riga di dati.
typedef char **MYSQL_ROW; /* return data as array of strings */
Ci metto pure il MYSQL_FIELD, visto che viene considerato dalla struct RES.
typedef struct st_mysql_field {
char *name; /* Name of column */
char *org_name; /* Original column name, if an alias */
char *table; /* Table of column if column was a field */
char *org_table; /* Org table name, if table was an alias */
char *db; /* Database for table */
char *catalog; /* Catalog for table */
char *def; /* Default value (set by mysql_list_fields) */
[... blah blah blah ...]
enum enum_field_types type; /* Type of field. See mysql_com.h for types */
} MYSQL_FIELD;