Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自增的主键设置 #20

Closed
boboxu opened this issue Jun 12, 2017 · 9 comments
Closed

自增的主键设置 #20

boboxu opened this issue Jun 12, 2017 · 9 comments

Comments

@boboxu
Copy link

boboxu commented Jun 12, 2017

WCDB_PRIMARY_ASC_AUTO_INCREMENT,自增的主键设置之后。
赋值操作不写这个字段。结果到后面insert第二个的时候,发现标记的字段并未自增。
insert操作报错:UNIQUE constraint failed

不知道是不是没有实现呢?
如果有实现的话,能否完善一下文档呢?谢谢了。

@alexlee002
Copy link

这里应该是个bug, 如果某个字段是int类型, 并且设置成primary key, 那么, 按照sqlite的文档, 它其实就是rowid的别名。 在生成insert语句的时候, 不应该把这个字段放到插入字段列表里边。(之前在做patchwork 实现ActiveRecord的时候就踩过这个坑)

另外, 想请问一下@RingoD , WCDB是不是已经在微信上广泛使用了?

@RingoD
Copy link
Collaborator

RingoD commented Jun 12, 2017

WCDB插入默认是使用不自增的,如需自增需设置isAutoIncrement,参考sample中的WCTSampleConvenient

WCTSampleConvenient *object = [[WCTSampleConvenient alloc] init];
object.isAutoIncrement = YES;
object.stringValue = @"Insert auto increment";

@RingoD
Copy link
Collaborator

RingoD commented Jun 12, 2017

@alexlee002 int类型的主键是rowid的别名,但没有“ 不应该把这个字段放到插入字段列表里边”这个说法。

@alexlee002
Copy link

alexlee002 commented Jun 12, 2017

@RingoD 可能我的表述不够清楚。 我的意思是, 如果字段 col_a是一个自增int主键字段, 那么如果执行下边的sql:

INSERT INTO table (col_a, col_b) VALUES(1, 'aaa');

那么, sqlite不会忽略自增设置, 直接用sql中指定的值。

所以, 如果需要让sqlite按照自增来自动设值, 那么sql应该是这样:

INSERT INTO table (col_b) VALUES('aaa');

@RingoD
Copy link
Collaborator

RingoD commented Jun 12, 2017

@alexlee002 这是两种不同的用法

第一种对应WCDB内的:

    /*
     INSERT INTO myTable(intValue, stringValue) VALUES(1, "aaa");
     */
    WCTSampleConvenient *object = [[WCTSampleConvenient alloc] init];
    object.intValue = 1;
    object.stringValue = @"aaa";
    [database insertObject:object into:@"myTable"];

第二种对应:

    /*
     INSERT INTO myTable(intValue, stringValue) VALUES(NULL, "aaa");
     */
    WCTSampleConvenient *object = [[WCTSampleConvenient alloc] init];
    object.isAutoIncrement = YES;
    object.stringValue = @"aaa";
    [database insertObject:object into:@"myTable"];

两种都是WCDB和sqlite正确的用法,不是bug

@alexlee002
Copy link

@RingoD 恩, 我之前没仔细看代码, 没有注意isAutoIncrement这个属性。

@boboxu
Copy link
Author

boboxu commented Jun 12, 2017

我也看到了。亲测 可用。 @RingoD @alexlee002

@zedzhao
Copy link

zedzhao commented Apr 15, 2019

测了下 将一个int型的数据用WCDB_PRIMARY_ASC_AUTO_INCREMENT 设置为主键后, 只要是insert数据 该字段就会一直增长,删除掉之前的数据 插入新数据时仍然是从之前最大的 rowID开始增长,这样的话如果这个id值达到了最大值根据sqlite的文档就没办法再插入新数据了?

@RingoD
Copy link
Collaborator

RingoD commented Apr 15, 2019

@zedzhao Don't reply here. Open your own issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants