mysql2sqlite.sh Auto_Increment

时间:2013-12-23 13:37:54

标签: mysql sqlite

原始MySQl Tbl_driver

delimiter $$

CREATE TABLE `tbl_driver` (
  `_id` int(11) NOT NULL AUTO_INCREMENT,
  `Driver_Code` varchar(45) NOT NULL,
  `Driver_Name` varchar(45) NOT NULL,
  `AddBy_ID` int(11) NOT NULL,
  PRIMARY KEY (`_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1$$

mysql2sqlite.sh

#!/bin/sh

# Converts a mysqldump file into a Sqlite 3 compatible file. It also extracts the MySQL `KEY xxxxx` from the
# CREATE block and create them in separate commands _after_ all the INSERTs.

# Awk is choosen because it's fast and portable. You can use gawk, original awk or even the lightning fast mawk.
# The mysqldump file is traversed only once.

# Usage: $ ./mysql2sqlite mysqldump-opts db-name | sqlite3 database.sqlite
# Example: $ ./mysql2sqlite --no-data -u root -pMySecretPassWord myDbase | sqlite3 database.sqlite

# Thanks to and @artemyk and @gkuenning for their nice tweaks.

mysqldump  --compatible=ansi --skip-extended-insert --compact  "$@" | \

awk '

BEGIN {
    FS=",$"
    print "PRAGMA synchronous = OFF;"
    print "PRAGMA journal_mode = MEMORY;"
    print "BEGIN TRANSACTION;"
}

# CREATE TRIGGER statements have funny commenting.  Remember we are in trigger.
/^\/\*.*CREATE.*TRIGGER/ {
    gsub( /^.*TRIGGER/, "CREATE TRIGGER" )
    print
    inTrigger = 1
    next
}

# The end of CREATE TRIGGER has a stray comment terminator
/END \*\/;;/ { gsub( /\*\//, "" ); print; inTrigger = 0; next }

# The rest of triggers just get passed through
inTrigger != 0 { print; next }

# Skip other comments
/^\/\*/ { next }

# Print all `INSERT` lines. The single quotes are protected by another single quote.
/INSERT/ {
    gsub( /\\\047/, "\047\047" )
    gsub(/\\n/, "\n")
    gsub(/\\r/, "\r")
    gsub(/\\"/, "\"")
    gsub(/\\\\/, "\\")
    gsub(/\\\032/, "\032")
    print
    next
}

# Print the `CREATE` line as is and capture the table name.
/^CREATE/ {
    print
    if ( match( $0, /\"[^\"]+/ ) ) tableName = substr( $0, RSTART+1, RLENGTH-1 ) 
}

# Replace `FULLTEXT KEY` or any other `XXXXX KEY` except PRIMARY by `KEY`
/^  [^"]+KEY/ && !/^  PRIMARY KEY/ { gsub( /.+KEY/, "  KEY" ) }

# Get rid of field lengths in KEY lines
/ KEY/ { gsub(/\([0-9]+\)/, "") }

# Print all fields definition lines except the `KEY` lines.
/^  / && !/^(  KEY|\);)/ {
    gsub( /AUTO_INCREMENT|auto_increment/, "" )
    gsub( /(CHARACTER SET|character set) [^ ]+ /, "" )
    gsub( /DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP|default current_timestamp on update current_timestamp/, "" )
    gsub( /(COLLATE|collate) [^ ]+ /, "" )
    gsub(/(ENUM|enum)[^)]+\)/, "text ")
    gsub(/(SET|set)\([^)]+\)/, "text ")
    gsub(/UNSIGNED|unsigned/, "")
    if (prev) print prev ","
    prev = $1
}

# `KEY` lines are extracted from the `CREATE` block and stored in array for later print 
# in a separate `CREATE KEY` command. The index name is prefixed by the table name to 
# avoid a sqlite error for duplicate index name.
/^(  KEY|\);)/ {
    if (prev) print prev
    prev=""
    if ($0 == ");"){
        print
    } else {
        if ( match( $0, /\"[^"]+/ ) ) indexName = substr( $0, RSTART+1, RLENGTH-1 ) 
        if ( match( $0, /\([^()]+/ ) ) indexKey = substr( $0, RSTART+1, RLENGTH-1 ) 
        key[tableName]=key[tableName] "CREATE INDEX \"" tableName "_" indexName "\" ON \"" tableName "\" (" indexKey ");\n"
    }
}

# Print all `KEY` creation lines.
END {
    for (table in key) printf key[table]
    print "END TRANSACTION;"
}
'
exit 0

执行此脚本时,我的sqlite数据库就像这样

Sqlite Tbl_Driver

CREATE TABLE "tbl_driver" (
  "_id" int(11) NOT NULL ,
  "Driver_Code" varchar(45) NOT NULL,
  "Driver_Name" varchar(45) NOT NULL,
  "AddBy_ID" int(11) NOT NULL,
  PRIMARY KEY ("_id")
)

我想更改"_id" int(11) NOT NULL ,
变得像这样"_id" int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,

变得像这样"_id" int(11) NOT NULL AUTO_INCREMENT,
 没有主键也可以

是否有修改此脚本的想法?

2 个答案:

答案 0 :(得分:4)

AUTO_INCREMENT关键字特定于MySQL。

SQLite有一个关键字AUTOINCREMENT(没有下划线),这意味着该列会自动生成以前从未在表中使用过的单调递增值。

如果省略AUTOINCREMENT关键字(正如您当前显示的脚本所做的那样),SQLite会将ROWID分配给新行,这意味着它将比表中当前最大的ROWID大1 。如果从表的高端删除行然后插入新行,则可以重用值。

有关详细信息,请参阅http://www.sqlite.org/autoinc.html

如果您想修改此脚本以添加AUTOINCREMENT关键字,您似乎可以修改此行:

gsub( /AUTO_INCREMENT|auto_increment/, "" )

对此:

gsub( /AUTO_INCREMENT|auto_increment/, "AUTOINCREMENT" )

重新评论:

好的,我在使用sqlite3的虚拟桌面上尝试过它。

sqlite> create table foo ( 
  i int autoincrement, 
  primary key (i)
);
Error: near "autoincrement": syntax error

显然,SQLite要求autoincrement遵循列级主键约束。作为表级约束,将pk约束放在最后的MySQL约定并不满意。 SQLite documentation for CREATE TABLE中的语法图支持这一点。

让我们尝试将primary key放在autoincrement之前。

sqlite> create table foo ( 
  i int primary key autoincrement
);
Error: AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY

显然SQLite不喜欢“INT”,它更喜欢“INTEGER”:

sqlite> create table foo (
  i integer primary key autoincrement
);
sqlite>

成功!

因此,您的awk脚本无法像您想象的那样轻松地将MySQL表DDL转换为SQLite。


重新评论:

您正在尝试复制名为SQL::Translator的Perl模块的工作,这是很多工作。我不会为你写一个完整的工作脚本。

要真正解决此问题,并创建一个可以自动执行所有语法更改以使DDL与SQLite兼容的脚本,您需要为SQL DDL实现完整的解析器。这在awk中不切实际。

我建议您使用脚本来解决关键字替换的部分,然后如果需要进一步更改,请在文本编辑器中手动修复它们。

还要考虑妥协。如果重新格式化DDL以使用SQLite中的AUTOINCREMENT功能太困难,请考虑默认的ROWID功能是否足够接近。阅读我上面发布的链接,了解其中的差异。

答案 1 :(得分:0)

我找到了一个奇怪的解决方案,但它适用于PHP Doctrine。

创建一个Mysql数据库。 从数据库创建Doctrine 2实体,弥补所有的一致性。

Doctrine 2具有将实体与数据库进行比较并修复数据库以验证实体的功能。

通过mysql2sqlite.sh导出数据库完全符合您的描述。

然后配置doctrine驱动程序以使用sqlite db和:

作曲家

vendor/bin/doctrine-module orm:schema-tool:update --force

它无需手头即可修复自动增量。