ラベル PostgreSQL の投稿を表示しています。 すべての投稿を表示
ラベル PostgreSQL の投稿を表示しています。 すべての投稿を表示

2013/06/26

[PostgreSQL] IDを 0埋めで 登録し直す

既に 登録済みの ID(1~連番)を 1で始まる全10桁の数値に 振り直したい

例)
旧ID 新ID
1 10000000001
2 10000000002
3 10000000003
4 10000000004
5 10000000005

↑こんな感じ

UPDATE table_name SET id= cast(1||lpad(''||id, 9, '0') as bigint);

●解説
lpad(''||id, 9, '0') 
→ 左埋め '0'(引数3番目)で9桁(引数2番目)0埋め(3番目省略すると、空白で埋められる)
→ ''||id は、idがbigintのため ''空文字列を結合して stringにしてやる(lpadの引数1番目はstringじゃないと怒られる)

cast(1||lpad(''||id, 9, '0') as bigint)
→ 0埋め処理した文字列を cast()で bigintに戻してます

2013/06/22

[CakePHP2.x][PostgreSQL] ConnectionManagerで DBのテーブルとフィールド定義を取得してみる

Class Postgres | CakePHP http://api.cakephp.org/2.3/class-Postgres.html

// getDataSource
$db = ConnectionManager::getDataSource(string Model::$useDbConfig);
  →Model::$useDbConfig databaseの設定名 'default'とか
  →ModelObject->useDbConfigで取れる e.g. $this->Model->useDbConfig

// an array of tables in the database.
$tables = $db->listSources();

// Fields in table. Keys are name and type
$data = array();
foreach ($tables as $table) {
  $fields = $db->describe(strtolower($table));
  $data[$table] = $fields;
}

// $dataに テーブルとフィールドの定義が入る
Array
(
    [table_name] => Array
        (
            [id] => Array
                (
                    [type] => integer
                    [null] =>
                    [default] =>
                    [length] =>
                )
            [name] => Array
                (
                    [type] => string
                    [null] =>
                    [default] =>
                    [length] => 512
                )
            [update_id] => Array
                (
                    [type] => text
                    [null] =>
                    [default] =>
                    [length] =>
                )

            [regist_date] => Array
                (
                    [type] => datetime
                    [null] =>
                    [default] =>
                    [length] =>
                )
        )
)