Skip to content

DSL for declaring code generation #7

@iOliverNguyen

Description

@iOliverNguyen

The first prototype employs goderive as DSL (example) for declaring code generation.

The next version should define its own DSL for more clarification and better error messages. The DSL can be put inside Go code or as separate files like protobuf. We don't intend to employ the whole SQL syntax, only a subset that makes sense.

Note that, unlike SQL, our keywords must be lowercase (generate) or uppercase (GENERATE) but not mixed (Generate or GeneRATE).

Generate structs from table

//sqlgen: generate from "user"
type User struct {
    ID   int64
    Name string
}

Short-hand syntax. Both struct and table name can be inferred from the struct.

//sqlgen: generate
type Account struct {
    ID   int64
    Name string
}

Full syntax with plural form:

//sqlgen: generate AccountUser (plural AccountUsers) from "account_user"
type AccountUser struct {
    AccountID int64
    UserID    int64
    Role      string
}

Join between multiple tables

//sqlgen: generate from "user"
//        join account_user on  "user".id = account_user.user_id
//        join account      on account.id = account_user.account_id
type UserJoinAccount struct {
    User        *User
    AccountUser *AccountUser
    Account     *Account
}

The above can be written in full syntax:

//sqlgen: generate UserJoinAccount (plural UserJoinAccounts)
//        from "user"         (User)        as u
//        join "account_user" (AccountUser) as au on u.id = au.user_id
//        join "account"      (Account)     as a  on a.id = au.account_id
type UserJoinAccount struct {
    User        *User
    AccountUser *AccountUser
    Account     *Account
}

All statements in a single comment block

/*
sqlgen:

generate User from "user";
generate Account from account;
generate AccountUser from account_user;
generate UserJoinAccount
  from "user"
  join account_user on  "user".id = account_user.user_id
  join account      on account.id = account_user.account_id
*/

Full syntax:

generate User (plural Users) from "user";
generate Account (plural Accounts) from "account";
generate AccountUser (plural AccountUsers) from "account_user";
generate UserJoinAccount 
  from "user"         (User)        as u
  join "account_user" (AccountUser) as au on u.id = au.user_id
  join "account"      (Account)     as a  on a.id = au.account_id;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions