2312d,d的sql构建器

原文
项目
该项目在我工作项目中广泛使用,它允许自动处理联接方式动态构建SQL语句.

还会自动直接按表示数据库行结构序化.它在dconf2022在线演讲中介绍了:建模一切.

刚刚添加了对sqlite的支持.该API还不稳定,但仍非常有用.这是按需构建,所以虽然有个计划外表,但满足了我的需要.
示例(使用sqlite):

import d2sqlite3;
import std.stdio;
import std.file : exists;
import std.array;
//是的,我知道,在此我需要一个包装
import sqlbuilder.uda;
import sqlbuilder.dataset;
import sqlbuilder.dialect.sqlite;
import sqlbuilder.types;
import d2sqlite3;
struct Author
{
    
    
    @primaryKey @autoIncrement int id;
    string firstname;
    string lastname;
    static @refersTo!Book @mapping("author_id") Relation books;
}
struct Book
{
    
    
    @primaryKey @autoIncrement int id;
    string title;
    string description;
    @mustReferTo!Author("author") int author_id;
}
void main()
{
    
    
    auto shouldInitialize = !exists("books.sqlite");
    auto db = Database("books.sqlite");
    if(shouldInitialize)
    {
    
    
        //创建表
        db.execute(createTableSql!Author);
        db.execute(createTableSql!Book);
        //添加一些书籍和作者
        Author walter = Author( firstname: "Walter", lastname: "Bright");
        db.create(walter); //按`SQL`插入语句自动序化
        Author andrei = Author( firstname: "Andrei", lastname: "Alexandrescu");
        db.create(andrei);
        db.create(Book(
                title: "D语言",
                description: "The OG D manual",
                author_id: andrei.id));
        db.create(Book(
                title: "C++ 设计",
                description: "The OG C++ template manual",
                author_id: andrei.id));
        db.create(Book(
                title: "D规范",
                description: "D语言规范",
                author_id: walter.id));
    }
    //按姓名取作者
    DataSet!Author ads;
    auto andrei = db.fetchOne(select(ads).where(ads.firstname, " = 'Andrei'"));
    //根据书籍的数据集来选择
    DataSet!Book bds;
    foreach(booktitle, author; db.fetch(select(bds.title, bds.author)))
    {
    
    
        writefln("Found book %s, written by %s %s", booktitle, author.firstname, author.lastname);
    }
    auto andreiBooks = db.fetch(select(bds)
        .where(bds.author_id, " = ", andrei.id.param)).array;
    writeln("Andrei's books: ", andreiBooks);
}

使用mysql的代码也类似,只需导入mysql-nativesqlbuilder.dialect.mysql即可.
接着是postgresql,不确定我何时需要构建它.
-史蒂夫

猜你喜欢

转载自blog.csdn.net/fqbqrr/article/details/135313199
d
<d>
d'd