feat: entities

This commit is contained in:
2025-03-09 21:51:16 +07:00
parent bd4be08c37
commit baf4c67cfb
21 changed files with 2171 additions and 62 deletions

View File

@@ -9,6 +9,7 @@ export class Author {
"Id": number; "Id": number;
"Name": string; "Name": string;
"Posts": Post[]; "Posts": Post[];
"Comments": Comment[];
/** Creates a new Author instance. */ /** Creates a new Author instance. */
constructor($$source: Partial<Author> = {}) { constructor($$source: Partial<Author> = {}) {
@@ -21,6 +22,9 @@ export class Author {
if (!("Posts" in $$source)) { if (!("Posts" in $$source)) {
this["Posts"] = []; this["Posts"] = [];
} }
if (!("Comments" in $$source)) {
this["Comments"] = [];
}
Object.assign(this, $$source); Object.assign(this, $$source);
} }
@@ -30,14 +34,63 @@ export class Author {
*/ */
static createFrom($$source: any = {}): Author { static createFrom($$source: any = {}): Author {
const $$createField2_0 = $$createType1; const $$createField2_0 = $$createType1;
const $$createField3_0 = $$createType3;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source; let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("Posts" in $$parsedSource) { if ("Posts" in $$parsedSource) {
$$parsedSource["Posts"] = $$createField2_0($$parsedSource["Posts"]); $$parsedSource["Posts"] = $$createField2_0($$parsedSource["Posts"]);
} }
if ("Comments" in $$parsedSource) {
$$parsedSource["Comments"] = $$createField3_0($$parsedSource["Comments"]);
}
return new Author($$parsedSource as Partial<Author>); return new Author($$parsedSource as Partial<Author>);
} }
} }
export class Comment {
"Id": number;
"Text": string;
"AuthorId": number;
"Author": Author;
"Posts": Post[];
/** Creates a new Comment instance. */
constructor($$source: Partial<Comment> = {}) {
if (!("Id" in $$source)) {
this["Id"] = 0;
}
if (!("Text" in $$source)) {
this["Text"] = "";
}
if (!("AuthorId" in $$source)) {
this["AuthorId"] = 0;
}
if (!("Author" in $$source)) {
this["Author"] = (new Author());
}
if (!("Posts" in $$source)) {
this["Posts"] = [];
}
Object.assign(this, $$source);
}
/**
* Creates a new Comment instance from a string or object.
*/
static createFrom($$source: any = {}): Comment {
const $$createField3_0 = $$createType4;
const $$createField4_0 = $$createType1;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("Author" in $$parsedSource) {
$$parsedSource["Author"] = $$createField3_0($$parsedSource["Author"]);
}
if ("Posts" in $$parsedSource) {
$$parsedSource["Posts"] = $$createField4_0($$parsedSource["Posts"]);
}
return new Comment($$parsedSource as Partial<Comment>);
}
}
export class Post { export class Post {
"Id": number; "Id": number;
"Text": string; "Text": string;
@@ -45,6 +98,9 @@ export class Post {
"CreatedAt": number; "CreatedAt": number;
"AuthorId": number; "AuthorId": number;
"Author": Author; "Author": Author;
"PostTypeId": number;
"PostType": PostType;
"Comments": Comment[];
/** Creates a new Post instance. */ /** Creates a new Post instance. */
constructor($$source: Partial<Post> = {}) { constructor($$source: Partial<Post> = {}) {
@@ -66,6 +122,15 @@ export class Post {
if (!("Author" in $$source)) { if (!("Author" in $$source)) {
this["Author"] = (new Author()); this["Author"] = (new Author());
} }
if (!("PostTypeId" in $$source)) {
this["PostTypeId"] = 0;
}
if (!("PostType" in $$source)) {
this["PostType"] = (new PostType());
}
if (!("Comments" in $$source)) {
this["Comments"] = [];
}
Object.assign(this, $$source); Object.assign(this, $$source);
} }
@@ -74,16 +139,52 @@ export class Post {
* Creates a new Post instance from a string or object. * Creates a new Post instance from a string or object.
*/ */
static createFrom($$source: any = {}): Post { static createFrom($$source: any = {}): Post {
const $$createField5_0 = $$createType2; const $$createField5_0 = $$createType4;
const $$createField7_0 = $$createType5;
const $$createField8_0 = $$createType3;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source; let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("Author" in $$parsedSource) { if ("Author" in $$parsedSource) {
$$parsedSource["Author"] = $$createField5_0($$parsedSource["Author"]); $$parsedSource["Author"] = $$createField5_0($$parsedSource["Author"]);
} }
if ("PostType" in $$parsedSource) {
$$parsedSource["PostType"] = $$createField7_0($$parsedSource["PostType"]);
}
if ("Comments" in $$parsedSource) {
$$parsedSource["Comments"] = $$createField8_0($$parsedSource["Comments"]);
}
return new Post($$parsedSource as Partial<Post>); return new Post($$parsedSource as Partial<Post>);
} }
} }
export class PostType {
"Id": number;
"Name": string;
/** Creates a new PostType instance. */
constructor($$source: Partial<PostType> = {}) {
if (!("Id" in $$source)) {
this["Id"] = 0;
}
if (!("Name" in $$source)) {
this["Name"] = "";
}
Object.assign(this, $$source);
}
/**
* Creates a new PostType instance from a string or object.
*/
static createFrom($$source: any = {}): PostType {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new PostType($$parsedSource as Partial<PostType>);
}
}
// Private type creation functions // Private type creation functions
const $$createType0 = Post.createFrom; const $$createType0 = Post.createFrom;
const $$createType1 = $Create.Array($$createType0); const $$createType1 = $Create.Array($$createType0);
const $$createType2 = Author.createFrom; const $$createType2 = Comment.createFrom;
const $$createType3 = $Create.Array($$createType2);
const $$createType4 = Author.createFrom;
const $$createType5 = PostType.createFrom;

View File

@@ -20,7 +20,7 @@ export function Count(): Promise<number> & { cancel(): void } {
export function Create(item: $models.Author): Promise<$models.Author> & { cancel(): void } { export function Create(item: $models.Author): Promise<$models.Author> & { cancel(): void } {
let $resultPromise = $Call.ByID(3684602449, item) as any; let $resultPromise = $Call.ByID(3684602449, item) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result); return $$createType0($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
@@ -34,7 +34,7 @@ export function Delete(id: number): Promise<void> & { cancel(): void } {
export function GetAll(): Promise<($models.Author | null)[]> & { cancel(): void } { export function GetAll(): Promise<($models.Author | null)[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(3248293926) as any; let $resultPromise = $Call.ByID(3248293926) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType2($result); return $$createType2($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
@@ -43,7 +43,7 @@ export function GetAll(): Promise<($models.Author | null)[]> & { cancel(): void
export function GetById(id: number): Promise<$models.Author | null> & { cancel(): void } { export function GetById(id: number): Promise<$models.Author | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(1703016211, id) as any; let $resultPromise = $Call.ByID(1703016211, id) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType1($result); return $$createType1($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
@@ -52,7 +52,7 @@ export function GetById(id: number): Promise<$models.Author | null> & { cancel()
export function Update(item: $models.Author): Promise<$models.Author> & { cancel(): void } { export function Update(item: $models.Author): Promise<$models.Author> & { cancel(): void } {
let $resultPromise = $Call.ByID(2240704960, item) as any; let $resultPromise = $Call.ByID(2240704960, item) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result); return $$createType0($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);

View File

@@ -0,0 +1,65 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import {Call as $Call, Create as $Create} from "@wailsio/runtime";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as models$0 from "../models/models.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as $models from "./models.js";
export function Count(): Promise<number> & { cancel(): void } {
let $resultPromise = $Call.ByID(3225397984) as any;
return $resultPromise;
}
export function Create(item: $models.Comment): Promise<$models.Comment> & { cancel(): void } {
let $resultPromise = $Call.ByID(4239106089, item) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
export function Delete(id: number): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(2553503582, id) as any;
return $resultPromise;
}
export function GetAll(): Promise<($models.Comment | null)[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(1805763390) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType2($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
export function GetById(id: number): Promise<$models.Comment | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(3217823099, id) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType1($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
export function Update(item: $models.Comment): Promise<$models.Comment> & { cancel(): void } {
let $resultPromise = $Call.ByID(3080970936, item) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
// Private type creation functions
const $$createType0 = models$0.Comment.createFrom;
const $$createType1 = $Create.Nullable($$createType0);
const $$createType2 = $Create.Array($$createType1);

View File

@@ -2,10 +2,14 @@
// This file is automatically generated. DO NOT EDIT // This file is automatically generated. DO NOT EDIT
import * as AuthorService from "./authorservice.js"; import * as AuthorService from "./authorservice.js";
import * as CommentService from "./commentservice.js";
import * as PostService from "./postservice.js"; import * as PostService from "./postservice.js";
import * as PostTypeService from "./posttypeservice.js";
export { export {
AuthorService, AuthorService,
PostService CommentService,
PostService,
PostTypeService
}; };
export * from "./models.js"; export * from "./models.js";

View File

@@ -12,5 +12,11 @@ import * as models$0 from "../models/models.js";
export const Author = models$0.Author; export const Author = models$0.Author;
export type Author = models$0.Author; export type Author = models$0.Author;
export const Comment = models$0.Comment;
export type Comment = models$0.Comment;
export const Post = models$0.Post; export const Post = models$0.Post;
export type Post = models$0.Post; export type Post = models$0.Post;
export const PostType = models$0.PostType;
export type PostType = models$0.PostType;

View File

@@ -20,7 +20,7 @@ export function Count(): Promise<number> & { cancel(): void } {
export function Create(item: $models.Post): Promise<$models.Post> & { cancel(): void } { export function Create(item: $models.Post): Promise<$models.Post> & { cancel(): void } {
let $resultPromise = $Call.ByID(1443399856, item) as any; let $resultPromise = $Call.ByID(1443399856, item) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result); return $$createType0($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
@@ -39,7 +39,7 @@ export function ExportToExcel(): Promise<void> & { cancel(): void } {
export function GetAll(): Promise<($models.Post | null)[]> & { cancel(): void } { export function GetAll(): Promise<($models.Post | null)[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(65691059) as any; let $resultPromise = $Call.ByID(65691059) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType2($result); return $$createType2($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
@@ -48,7 +48,7 @@ export function GetAll(): Promise<($models.Post | null)[]> & { cancel(): void }
export function GetById(id: number): Promise<$models.Post | null> & { cancel(): void } { export function GetById(id: number): Promise<$models.Post | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(4074736792, id) as any; let $resultPromise = $Call.ByID(4074736792, id) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType1($result); return $$createType1($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
@@ -57,7 +57,7 @@ export function GetById(id: number): Promise<$models.Post | null> & { cancel():
export function Update(item: $models.Post): Promise<$models.Post> & { cancel(): void } { export function Update(item: $models.Post): Promise<$models.Post> & { cancel(): void } {
let $resultPromise = $Call.ByID(137798821, item) as any; let $resultPromise = $Call.ByID(137798821, item) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result); return $$createType0($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);

View File

@@ -0,0 +1,65 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import {Call as $Call, Create as $Create} from "@wailsio/runtime";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as models$0 from "../models/models.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as $models from "./models.js";
export function Count(): Promise<number> & { cancel(): void } {
let $resultPromise = $Call.ByID(554487955) as any;
return $resultPromise;
}
export function Create(item: $models.PostType): Promise<$models.PostType> & { cancel(): void } {
let $resultPromise = $Call.ByID(1092898136, item) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
export function Delete(id: number): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(2114913543, id) as any;
return $resultPromise;
}
export function GetAll(): Promise<($models.PostType | null)[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(416231387) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType2($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
export function GetById(id: number): Promise<$models.PostType | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(3237123344, id) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType1($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
export function Update(item: $models.PostType): Promise<$models.PostType> & { cancel(): void } {
let $resultPromise = $Call.ByID(2773888269, item) as any;
let $typingPromise = $resultPromise.then(($result) => {
return $$createType0($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
// Private type creation functions
const $$createType0 = models$0.PostType.createFrom;
const $$createType1 = $Create.Nullable($$createType0);
const $$createType2 = $Create.Array($$createType1);

View File

@@ -37,6 +37,15 @@ func newAuthor(db *gorm.DB, opts ...gen.DOOption) author {
Posts struct { Posts struct {
field.RelationField field.RelationField
} }
Comments struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}
}{ }{
RelationField: field.NewRelation("Posts.Author", "models.Author"), RelationField: field.NewRelation("Posts.Author", "models.Author"),
Posts: struct { Posts: struct {
@@ -44,7 +53,44 @@ func newAuthor(db *gorm.DB, opts ...gen.DOOption) author {
}{ }{
RelationField: field.NewRelation("Posts.Author.Posts", "models.Post"), RelationField: field.NewRelation("Posts.Author.Posts", "models.Post"),
}, },
Comments: struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}{
RelationField: field.NewRelation("Posts.Author.Comments", "models.Comment"),
Author: struct {
field.RelationField
}{
RelationField: field.NewRelation("Posts.Author.Comments.Author", "models.Author"),
},
Posts: struct {
field.RelationField
}{
RelationField: field.NewRelation("Posts.Author.Comments.Posts", "models.Post"),
},
},
}, },
PostType: struct {
field.RelationField
}{
RelationField: field.NewRelation("Posts.PostType", "models.PostType"),
},
Comments: struct {
field.RelationField
}{
RelationField: field.NewRelation("Posts.Comments", "models.Comment"),
},
}
_author.Comments = authorHasManyComments{
db: db.Session(&gorm.Session{}),
RelationField: field.NewRelation("Comments", "models.Comment"),
} }
_author.fillFieldMap() _author.fillFieldMap()
@@ -60,6 +106,8 @@ type author struct {
Name field.String Name field.String
Posts authorHasManyPosts Posts authorHasManyPosts
Comments authorHasManyComments
fieldMap map[string]field.Expr fieldMap map[string]field.Expr
} }
@@ -93,7 +141,7 @@ func (a *author) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
} }
func (a *author) fillFieldMap() { func (a *author) fillFieldMap() {
a.fieldMap = make(map[string]field.Expr, 3) a.fieldMap = make(map[string]field.Expr, 4)
a.fieldMap["id"] = a.Id a.fieldMap["id"] = a.Id
a.fieldMap["name"] = a.Name a.fieldMap["name"] = a.Name
@@ -119,6 +167,21 @@ type authorHasManyPosts struct {
Posts struct { Posts struct {
field.RelationField field.RelationField
} }
Comments struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}
}
PostType struct {
field.RelationField
}
Comments struct {
field.RelationField
} }
} }
@@ -187,6 +250,77 @@ func (a authorHasManyPostsTx) Count() int64 {
return a.tx.Count() return a.tx.Count()
} }
type authorHasManyComments struct {
db *gorm.DB
field.RelationField
}
func (a authorHasManyComments) Where(conds ...field.Expr) *authorHasManyComments {
if len(conds) == 0 {
return &a
}
exprs := make([]clause.Expression, 0, len(conds))
for _, cond := range conds {
exprs = append(exprs, cond.BeCond().(clause.Expression))
}
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
return &a
}
func (a authorHasManyComments) WithContext(ctx context.Context) *authorHasManyComments {
a.db = a.db.WithContext(ctx)
return &a
}
func (a authorHasManyComments) Session(session *gorm.Session) *authorHasManyComments {
a.db = a.db.Session(session)
return &a
}
func (a authorHasManyComments) Model(m *models.Author) *authorHasManyCommentsTx {
return &authorHasManyCommentsTx{a.db.Model(m).Association(a.Name())}
}
type authorHasManyCommentsTx struct{ tx *gorm.Association }
func (a authorHasManyCommentsTx) Find() (result []*models.Comment, err error) {
return result, a.tx.Find(&result)
}
func (a authorHasManyCommentsTx) Append(values ...*models.Comment) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Append(targetValues...)
}
func (a authorHasManyCommentsTx) Replace(values ...*models.Comment) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Replace(targetValues...)
}
func (a authorHasManyCommentsTx) Delete(values ...*models.Comment) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Delete(targetValues...)
}
func (a authorHasManyCommentsTx) Clear() error {
return a.tx.Clear()
}
func (a authorHasManyCommentsTx) Count() int64 {
return a.tx.Count()
}
type authorDo struct{ gen.DO } type authorDo struct{ gen.DO }
type IAuthorDo interface { type IAuthorDo interface {

View File

@@ -0,0 +1,622 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package dal
import (
"app/internal/models"
"context"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
)
func newComment(db *gorm.DB, opts ...gen.DOOption) comment {
_comment := comment{}
_comment.commentDo.UseDB(db, opts...)
_comment.commentDo.UseModel(&models.Comment{})
tableName := _comment.commentDo.TableName()
_comment.ALL = field.NewAsterisk(tableName)
_comment.Id = field.NewUint(tableName, "id")
_comment.Text = field.NewString(tableName, "text")
_comment.AuthorId = field.NewUint(tableName, "author_id")
_comment.Author = commentHasOneAuthor{
db: db.Session(&gorm.Session{}),
RelationField: field.NewRelation("Author", "models.Author"),
Posts: struct {
field.RelationField
Author struct {
field.RelationField
}
PostType struct {
field.RelationField
}
Comments struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}
}{
RelationField: field.NewRelation("Author.Posts", "models.Post"),
Author: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Posts.Author", "models.Author"),
},
PostType: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Posts.PostType", "models.PostType"),
},
Comments: struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}{
RelationField: field.NewRelation("Author.Posts.Comments", "models.Comment"),
Author: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Posts.Comments.Author", "models.Author"),
},
Posts: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Posts.Comments.Posts", "models.Post"),
},
},
},
Comments: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Comments", "models.Comment"),
},
}
_comment.Posts = commentManyToManyPosts{
db: db.Session(&gorm.Session{}),
RelationField: field.NewRelation("Posts", "models.Post"),
}
_comment.fillFieldMap()
return _comment
}
type comment struct {
commentDo
ALL field.Asterisk
Id field.Uint
Text field.String
AuthorId field.Uint
Author commentHasOneAuthor
Posts commentManyToManyPosts
fieldMap map[string]field.Expr
}
func (c comment) Table(newTableName string) *comment {
c.commentDo.UseTable(newTableName)
return c.updateTableName(newTableName)
}
func (c comment) As(alias string) *comment {
c.commentDo.DO = *(c.commentDo.As(alias).(*gen.DO))
return c.updateTableName(alias)
}
func (c *comment) updateTableName(table string) *comment {
c.ALL = field.NewAsterisk(table)
c.Id = field.NewUint(table, "id")
c.Text = field.NewString(table, "text")
c.AuthorId = field.NewUint(table, "author_id")
c.fillFieldMap()
return c
}
func (c *comment) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := c.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (c *comment) fillFieldMap() {
c.fieldMap = make(map[string]field.Expr, 5)
c.fieldMap["id"] = c.Id
c.fieldMap["text"] = c.Text
c.fieldMap["author_id"] = c.AuthorId
}
func (c comment) clone(db *gorm.DB) comment {
c.commentDo.ReplaceConnPool(db.Statement.ConnPool)
return c
}
func (c comment) replaceDB(db *gorm.DB) comment {
c.commentDo.ReplaceDB(db)
return c
}
type commentHasOneAuthor struct {
db *gorm.DB
field.RelationField
Posts struct {
field.RelationField
Author struct {
field.RelationField
}
PostType struct {
field.RelationField
}
Comments struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}
}
Comments struct {
field.RelationField
}
}
func (a commentHasOneAuthor) Where(conds ...field.Expr) *commentHasOneAuthor {
if len(conds) == 0 {
return &a
}
exprs := make([]clause.Expression, 0, len(conds))
for _, cond := range conds {
exprs = append(exprs, cond.BeCond().(clause.Expression))
}
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
return &a
}
func (a commentHasOneAuthor) WithContext(ctx context.Context) *commentHasOneAuthor {
a.db = a.db.WithContext(ctx)
return &a
}
func (a commentHasOneAuthor) Session(session *gorm.Session) *commentHasOneAuthor {
a.db = a.db.Session(session)
return &a
}
func (a commentHasOneAuthor) Model(m *models.Comment) *commentHasOneAuthorTx {
return &commentHasOneAuthorTx{a.db.Model(m).Association(a.Name())}
}
type commentHasOneAuthorTx struct{ tx *gorm.Association }
func (a commentHasOneAuthorTx) Find() (result *models.Author, err error) {
return result, a.tx.Find(&result)
}
func (a commentHasOneAuthorTx) Append(values ...*models.Author) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Append(targetValues...)
}
func (a commentHasOneAuthorTx) Replace(values ...*models.Author) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Replace(targetValues...)
}
func (a commentHasOneAuthorTx) Delete(values ...*models.Author) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Delete(targetValues...)
}
func (a commentHasOneAuthorTx) Clear() error {
return a.tx.Clear()
}
func (a commentHasOneAuthorTx) Count() int64 {
return a.tx.Count()
}
type commentManyToManyPosts struct {
db *gorm.DB
field.RelationField
}
func (a commentManyToManyPosts) Where(conds ...field.Expr) *commentManyToManyPosts {
if len(conds) == 0 {
return &a
}
exprs := make([]clause.Expression, 0, len(conds))
for _, cond := range conds {
exprs = append(exprs, cond.BeCond().(clause.Expression))
}
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
return &a
}
func (a commentManyToManyPosts) WithContext(ctx context.Context) *commentManyToManyPosts {
a.db = a.db.WithContext(ctx)
return &a
}
func (a commentManyToManyPosts) Session(session *gorm.Session) *commentManyToManyPosts {
a.db = a.db.Session(session)
return &a
}
func (a commentManyToManyPosts) Model(m *models.Comment) *commentManyToManyPostsTx {
return &commentManyToManyPostsTx{a.db.Model(m).Association(a.Name())}
}
type commentManyToManyPostsTx struct{ tx *gorm.Association }
func (a commentManyToManyPostsTx) Find() (result []*models.Post, err error) {
return result, a.tx.Find(&result)
}
func (a commentManyToManyPostsTx) Append(values ...*models.Post) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Append(targetValues...)
}
func (a commentManyToManyPostsTx) Replace(values ...*models.Post) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Replace(targetValues...)
}
func (a commentManyToManyPostsTx) Delete(values ...*models.Post) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Delete(targetValues...)
}
func (a commentManyToManyPostsTx) Clear() error {
return a.tx.Clear()
}
func (a commentManyToManyPostsTx) Count() int64 {
return a.tx.Count()
}
type commentDo struct{ gen.DO }
type ICommentDo interface {
gen.SubQuery
Debug() ICommentDo
WithContext(ctx context.Context) ICommentDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() ICommentDo
WriteDB() ICommentDo
As(alias string) gen.Dao
Session(config *gorm.Session) ICommentDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) ICommentDo
Not(conds ...gen.Condition) ICommentDo
Or(conds ...gen.Condition) ICommentDo
Select(conds ...field.Expr) ICommentDo
Where(conds ...gen.Condition) ICommentDo
Order(conds ...field.Expr) ICommentDo
Distinct(cols ...field.Expr) ICommentDo
Omit(cols ...field.Expr) ICommentDo
Join(table schema.Tabler, on ...field.Expr) ICommentDo
LeftJoin(table schema.Tabler, on ...field.Expr) ICommentDo
RightJoin(table schema.Tabler, on ...field.Expr) ICommentDo
Group(cols ...field.Expr) ICommentDo
Having(conds ...gen.Condition) ICommentDo
Limit(limit int) ICommentDo
Offset(offset int) ICommentDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) ICommentDo
Unscoped() ICommentDo
Create(values ...*models.Comment) error
CreateInBatches(values []*models.Comment, batchSize int) error
Save(values ...*models.Comment) error
First() (*models.Comment, error)
Take() (*models.Comment, error)
Last() (*models.Comment, error)
Find() ([]*models.Comment, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Comment, err error)
FindInBatches(result *[]*models.Comment, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*models.Comment) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) ICommentDo
Assign(attrs ...field.AssignExpr) ICommentDo
Joins(fields ...field.RelationField) ICommentDo
Preload(fields ...field.RelationField) ICommentDo
FirstOrInit() (*models.Comment, error)
FirstOrCreate() (*models.Comment, error)
FindByPage(offset int, limit int) (result []*models.Comment, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) ICommentDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (c commentDo) Debug() ICommentDo {
return c.withDO(c.DO.Debug())
}
func (c commentDo) WithContext(ctx context.Context) ICommentDo {
return c.withDO(c.DO.WithContext(ctx))
}
func (c commentDo) ReadDB() ICommentDo {
return c.Clauses(dbresolver.Read)
}
func (c commentDo) WriteDB() ICommentDo {
return c.Clauses(dbresolver.Write)
}
func (c commentDo) Session(config *gorm.Session) ICommentDo {
return c.withDO(c.DO.Session(config))
}
func (c commentDo) Clauses(conds ...clause.Expression) ICommentDo {
return c.withDO(c.DO.Clauses(conds...))
}
func (c commentDo) Returning(value interface{}, columns ...string) ICommentDo {
return c.withDO(c.DO.Returning(value, columns...))
}
func (c commentDo) Not(conds ...gen.Condition) ICommentDo {
return c.withDO(c.DO.Not(conds...))
}
func (c commentDo) Or(conds ...gen.Condition) ICommentDo {
return c.withDO(c.DO.Or(conds...))
}
func (c commentDo) Select(conds ...field.Expr) ICommentDo {
return c.withDO(c.DO.Select(conds...))
}
func (c commentDo) Where(conds ...gen.Condition) ICommentDo {
return c.withDO(c.DO.Where(conds...))
}
func (c commentDo) Order(conds ...field.Expr) ICommentDo {
return c.withDO(c.DO.Order(conds...))
}
func (c commentDo) Distinct(cols ...field.Expr) ICommentDo {
return c.withDO(c.DO.Distinct(cols...))
}
func (c commentDo) Omit(cols ...field.Expr) ICommentDo {
return c.withDO(c.DO.Omit(cols...))
}
func (c commentDo) Join(table schema.Tabler, on ...field.Expr) ICommentDo {
return c.withDO(c.DO.Join(table, on...))
}
func (c commentDo) LeftJoin(table schema.Tabler, on ...field.Expr) ICommentDo {
return c.withDO(c.DO.LeftJoin(table, on...))
}
func (c commentDo) RightJoin(table schema.Tabler, on ...field.Expr) ICommentDo {
return c.withDO(c.DO.RightJoin(table, on...))
}
func (c commentDo) Group(cols ...field.Expr) ICommentDo {
return c.withDO(c.DO.Group(cols...))
}
func (c commentDo) Having(conds ...gen.Condition) ICommentDo {
return c.withDO(c.DO.Having(conds...))
}
func (c commentDo) Limit(limit int) ICommentDo {
return c.withDO(c.DO.Limit(limit))
}
func (c commentDo) Offset(offset int) ICommentDo {
return c.withDO(c.DO.Offset(offset))
}
func (c commentDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ICommentDo {
return c.withDO(c.DO.Scopes(funcs...))
}
func (c commentDo) Unscoped() ICommentDo {
return c.withDO(c.DO.Unscoped())
}
func (c commentDo) Create(values ...*models.Comment) error {
if len(values) == 0 {
return nil
}
return c.DO.Create(values)
}
func (c commentDo) CreateInBatches(values []*models.Comment, batchSize int) error {
return c.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (c commentDo) Save(values ...*models.Comment) error {
if len(values) == 0 {
return nil
}
return c.DO.Save(values)
}
func (c commentDo) First() (*models.Comment, error) {
if result, err := c.DO.First(); err != nil {
return nil, err
} else {
return result.(*models.Comment), nil
}
}
func (c commentDo) Take() (*models.Comment, error) {
if result, err := c.DO.Take(); err != nil {
return nil, err
} else {
return result.(*models.Comment), nil
}
}
func (c commentDo) Last() (*models.Comment, error) {
if result, err := c.DO.Last(); err != nil {
return nil, err
} else {
return result.(*models.Comment), nil
}
}
func (c commentDo) Find() ([]*models.Comment, error) {
result, err := c.DO.Find()
return result.([]*models.Comment), err
}
func (c commentDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Comment, err error) {
buf := make([]*models.Comment, 0, batchSize)
err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (c commentDo) FindInBatches(result *[]*models.Comment, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return c.DO.FindInBatches(result, batchSize, fc)
}
func (c commentDo) Attrs(attrs ...field.AssignExpr) ICommentDo {
return c.withDO(c.DO.Attrs(attrs...))
}
func (c commentDo) Assign(attrs ...field.AssignExpr) ICommentDo {
return c.withDO(c.DO.Assign(attrs...))
}
func (c commentDo) Joins(fields ...field.RelationField) ICommentDo {
for _, _f := range fields {
c = *c.withDO(c.DO.Joins(_f))
}
return &c
}
func (c commentDo) Preload(fields ...field.RelationField) ICommentDo {
for _, _f := range fields {
c = *c.withDO(c.DO.Preload(_f))
}
return &c
}
func (c commentDo) FirstOrInit() (*models.Comment, error) {
if result, err := c.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*models.Comment), nil
}
}
func (c commentDo) FirstOrCreate() (*models.Comment, error) {
if result, err := c.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*models.Comment), nil
}
}
func (c commentDo) FindByPage(offset int, limit int) (result []*models.Comment, count int64, err error) {
result, err = c.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = c.Offset(-1).Limit(-1).Count()
return
}
func (c commentDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = c.Count()
if err != nil {
return
}
err = c.Offset(offset).Limit(limit).Scan(result)
return
}
func (c commentDo) Scan(result interface{}) (err error) {
return c.DO.Scan(result)
}
func (c commentDo) Delete(models ...*models.Comment) (result gen.ResultInfo, err error) {
return c.DO.Delete(models)
}
func (c *commentDo) withDO(do gen.Dao) *commentDo {
c.DO = *do.(*gen.DO)
return c
}

View File

@@ -0,0 +1,145 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package dal
import (
"app/internal/models"
"context"
"fmt"
"testing"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/gorm/clause"
)
func init() {
InitializeDB()
err := _gen_test_db.AutoMigrate(&models.Comment{})
if err != nil {
fmt.Printf("Error: AutoMigrate(&models.Comment{}) fail: %s", err)
}
}
func Test_commentQuery(t *testing.T) {
comment := newComment(_gen_test_db)
comment = *comment.As(comment.TableName())
_do := comment.WithContext(context.Background()).Debug()
primaryKey := field.NewString(comment.TableName(), clause.PrimaryKey)
_, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete()
if err != nil {
t.Error("clean table <comments> fail:", err)
return
}
_, ok := comment.GetFieldByName("")
if ok {
t.Error("GetFieldByName(\"\") from comment success")
}
err = _do.Create(&models.Comment{})
if err != nil {
t.Error("create item in table <comments> fail:", err)
}
err = _do.Save(&models.Comment{})
if err != nil {
t.Error("create item in table <comments> fail:", err)
}
err = _do.CreateInBatches([]*models.Comment{{}, {}}, 10)
if err != nil {
t.Error("create item in table <comments> fail:", err)
}
_, err = _do.Select(comment.ALL).Take()
if err != nil {
t.Error("Take() on table <comments> fail:", err)
}
_, err = _do.First()
if err != nil {
t.Error("First() on table <comments> fail:", err)
}
_, err = _do.Last()
if err != nil {
t.Error("First() on table <comments> fail:", err)
}
_, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil })
if err != nil {
t.Error("FindInBatch() on table <comments> fail:", err)
}
err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*models.Comment{}, 10, func(tx gen.Dao, batch int) error { return nil })
if err != nil {
t.Error("FindInBatches() on table <comments> fail:", err)
}
_, err = _do.Select(comment.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find()
if err != nil {
t.Error("Find() on table <comments> fail:", err)
}
_, err = _do.Distinct(primaryKey).Take()
if err != nil {
t.Error("select Distinct() on table <comments> fail:", err)
}
_, err = _do.Select(comment.ALL).Omit(primaryKey).Take()
if err != nil {
t.Error("Omit() on table <comments> fail:", err)
}
_, err = _do.Group(primaryKey).Find()
if err != nil {
t.Error("Group() on table <comments> fail:", err)
}
_, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find()
if err != nil {
t.Error("Scopes() on table <comments> fail:", err)
}
_, _, err = _do.FindByPage(0, 1)
if err != nil {
t.Error("FindByPage() on table <comments> fail:", err)
}
_, err = _do.ScanByPage(&models.Comment{}, 0, 1)
if err != nil {
t.Error("ScanByPage() on table <comments> fail:", err)
}
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit()
if err != nil {
t.Error("FirstOrInit() on table <comments> fail:", err)
}
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate()
if err != nil {
t.Error("FirstOrCreate() on table <comments> fail:", err)
}
var _a _another
var _aPK = field.NewString(_a.TableName(), "id")
err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
if err != nil {
t.Error("Join() on table <comments> fail:", err)
}
err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
if err != nil {
t.Error("LeftJoin() on table <comments> fail:", err)
}
_, err = _do.Not().Or().Clauses().Take()
if err != nil {
t.Error("Not/Or/Clauses on table <comments> fail:", err)
}
}

View File

@@ -16,39 +16,49 @@ import (
) )
var ( var (
Q = new(Query) Q = new(Query)
Author *author Author *author
Post *post Comment *comment
Post *post
PostType *postType
) )
func SetDefault(db *gorm.DB, opts ...gen.DOOption) { func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
*Q = *Use(db, opts...) *Q = *Use(db, opts...)
Author = &Q.Author Author = &Q.Author
Comment = &Q.Comment
Post = &Q.Post Post = &Q.Post
PostType = &Q.PostType
} }
func Use(db *gorm.DB, opts ...gen.DOOption) *Query { func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
return &Query{ return &Query{
db: db, db: db,
Author: newAuthor(db, opts...), Author: newAuthor(db, opts...),
Post: newPost(db, opts...), Comment: newComment(db, opts...),
Post: newPost(db, opts...),
PostType: newPostType(db, opts...),
} }
} }
type Query struct { type Query struct {
db *gorm.DB db *gorm.DB
Author author Author author
Post post Comment comment
Post post
PostType postType
} }
func (q *Query) Available() bool { return q.db != nil } func (q *Query) Available() bool { return q.db != nil }
func (q *Query) clone(db *gorm.DB) *Query { func (q *Query) clone(db *gorm.DB) *Query {
return &Query{ return &Query{
db: db, db: db,
Author: q.Author.clone(db), Author: q.Author.clone(db),
Post: q.Post.clone(db), Comment: q.Comment.clone(db),
Post: q.Post.clone(db),
PostType: q.PostType.clone(db),
} }
} }
@@ -62,21 +72,27 @@ func (q *Query) WriteDB() *Query {
func (q *Query) ReplaceDB(db *gorm.DB) *Query { func (q *Query) ReplaceDB(db *gorm.DB) *Query {
return &Query{ return &Query{
db: db, db: db,
Author: q.Author.replaceDB(db), Author: q.Author.replaceDB(db),
Post: q.Post.replaceDB(db), Comment: q.Comment.replaceDB(db),
Post: q.Post.replaceDB(db),
PostType: q.PostType.replaceDB(db),
} }
} }
type queryCtx struct { type queryCtx struct {
Author IAuthorDo Author IAuthorDo
Post IPostDo Comment ICommentDo
Post IPostDo
PostType IPostTypeDo
} }
func (q *Query) WithContext(ctx context.Context) *queryCtx { func (q *Query) WithContext(ctx context.Context) *queryCtx {
return &queryCtx{ return &queryCtx{
Author: q.Author.WithContext(ctx), Author: q.Author.WithContext(ctx),
Post: q.Post.WithContext(ctx), Comment: q.Comment.WithContext(ctx),
Post: q.Post.WithContext(ctx),
PostType: q.PostType.WithContext(ctx),
} }
} }

View File

@@ -78,7 +78,9 @@ func Test_WithContext(t *testing.T) {
for _, ctx := range []context.Context{ for _, ctx := range []context.Context{
qCtx.Author.UnderlyingDB().Statement.Context, qCtx.Author.UnderlyingDB().Statement.Context,
qCtx.Comment.UnderlyingDB().Statement.Context,
qCtx.Post.UnderlyingDB().Statement.Context, qCtx.Post.UnderlyingDB().Statement.Context,
qCtx.PostType.UnderlyingDB().Statement.Context,
} { } {
if v := ctx.Value(key); v != value { if v := ctx.Value(key); v != value {
t.Errorf("get value from context fail, expect %q, got %q", value, v) t.Errorf("get value from context fail, expect %q, got %q", value, v)

View File

@@ -0,0 +1,383 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package dal
import (
"app/internal/models"
"context"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
)
func newPostType(db *gorm.DB, opts ...gen.DOOption) postType {
_postType := postType{}
_postType.postTypeDo.UseDB(db, opts...)
_postType.postTypeDo.UseModel(&models.PostType{})
tableName := _postType.postTypeDo.TableName()
_postType.ALL = field.NewAsterisk(tableName)
_postType.Id = field.NewUint(tableName, "id")
_postType.Name = field.NewString(tableName, "name")
_postType.fillFieldMap()
return _postType
}
type postType struct {
postTypeDo
ALL field.Asterisk
Id field.Uint
Name field.String
fieldMap map[string]field.Expr
}
func (p postType) Table(newTableName string) *postType {
p.postTypeDo.UseTable(newTableName)
return p.updateTableName(newTableName)
}
func (p postType) As(alias string) *postType {
p.postTypeDo.DO = *(p.postTypeDo.As(alias).(*gen.DO))
return p.updateTableName(alias)
}
func (p *postType) updateTableName(table string) *postType {
p.ALL = field.NewAsterisk(table)
p.Id = field.NewUint(table, "id")
p.Name = field.NewString(table, "name")
p.fillFieldMap()
return p
}
func (p *postType) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := p.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (p *postType) fillFieldMap() {
p.fieldMap = make(map[string]field.Expr, 2)
p.fieldMap["id"] = p.Id
p.fieldMap["name"] = p.Name
}
func (p postType) clone(db *gorm.DB) postType {
p.postTypeDo.ReplaceConnPool(db.Statement.ConnPool)
return p
}
func (p postType) replaceDB(db *gorm.DB) postType {
p.postTypeDo.ReplaceDB(db)
return p
}
type postTypeDo struct{ gen.DO }
type IPostTypeDo interface {
gen.SubQuery
Debug() IPostTypeDo
WithContext(ctx context.Context) IPostTypeDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() IPostTypeDo
WriteDB() IPostTypeDo
As(alias string) gen.Dao
Session(config *gorm.Session) IPostTypeDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) IPostTypeDo
Not(conds ...gen.Condition) IPostTypeDo
Or(conds ...gen.Condition) IPostTypeDo
Select(conds ...field.Expr) IPostTypeDo
Where(conds ...gen.Condition) IPostTypeDo
Order(conds ...field.Expr) IPostTypeDo
Distinct(cols ...field.Expr) IPostTypeDo
Omit(cols ...field.Expr) IPostTypeDo
Join(table schema.Tabler, on ...field.Expr) IPostTypeDo
LeftJoin(table schema.Tabler, on ...field.Expr) IPostTypeDo
RightJoin(table schema.Tabler, on ...field.Expr) IPostTypeDo
Group(cols ...field.Expr) IPostTypeDo
Having(conds ...gen.Condition) IPostTypeDo
Limit(limit int) IPostTypeDo
Offset(offset int) IPostTypeDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) IPostTypeDo
Unscoped() IPostTypeDo
Create(values ...*models.PostType) error
CreateInBatches(values []*models.PostType, batchSize int) error
Save(values ...*models.PostType) error
First() (*models.PostType, error)
Take() (*models.PostType, error)
Last() (*models.PostType, error)
Find() ([]*models.PostType, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.PostType, err error)
FindInBatches(result *[]*models.PostType, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*models.PostType) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) IPostTypeDo
Assign(attrs ...field.AssignExpr) IPostTypeDo
Joins(fields ...field.RelationField) IPostTypeDo
Preload(fields ...field.RelationField) IPostTypeDo
FirstOrInit() (*models.PostType, error)
FirstOrCreate() (*models.PostType, error)
FindByPage(offset int, limit int) (result []*models.PostType, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) IPostTypeDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (p postTypeDo) Debug() IPostTypeDo {
return p.withDO(p.DO.Debug())
}
func (p postTypeDo) WithContext(ctx context.Context) IPostTypeDo {
return p.withDO(p.DO.WithContext(ctx))
}
func (p postTypeDo) ReadDB() IPostTypeDo {
return p.Clauses(dbresolver.Read)
}
func (p postTypeDo) WriteDB() IPostTypeDo {
return p.Clauses(dbresolver.Write)
}
func (p postTypeDo) Session(config *gorm.Session) IPostTypeDo {
return p.withDO(p.DO.Session(config))
}
func (p postTypeDo) Clauses(conds ...clause.Expression) IPostTypeDo {
return p.withDO(p.DO.Clauses(conds...))
}
func (p postTypeDo) Returning(value interface{}, columns ...string) IPostTypeDo {
return p.withDO(p.DO.Returning(value, columns...))
}
func (p postTypeDo) Not(conds ...gen.Condition) IPostTypeDo {
return p.withDO(p.DO.Not(conds...))
}
func (p postTypeDo) Or(conds ...gen.Condition) IPostTypeDo {
return p.withDO(p.DO.Or(conds...))
}
func (p postTypeDo) Select(conds ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.Select(conds...))
}
func (p postTypeDo) Where(conds ...gen.Condition) IPostTypeDo {
return p.withDO(p.DO.Where(conds...))
}
func (p postTypeDo) Order(conds ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.Order(conds...))
}
func (p postTypeDo) Distinct(cols ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.Distinct(cols...))
}
func (p postTypeDo) Omit(cols ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.Omit(cols...))
}
func (p postTypeDo) Join(table schema.Tabler, on ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.Join(table, on...))
}
func (p postTypeDo) LeftJoin(table schema.Tabler, on ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.LeftJoin(table, on...))
}
func (p postTypeDo) RightJoin(table schema.Tabler, on ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.RightJoin(table, on...))
}
func (p postTypeDo) Group(cols ...field.Expr) IPostTypeDo {
return p.withDO(p.DO.Group(cols...))
}
func (p postTypeDo) Having(conds ...gen.Condition) IPostTypeDo {
return p.withDO(p.DO.Having(conds...))
}
func (p postTypeDo) Limit(limit int) IPostTypeDo {
return p.withDO(p.DO.Limit(limit))
}
func (p postTypeDo) Offset(offset int) IPostTypeDo {
return p.withDO(p.DO.Offset(offset))
}
func (p postTypeDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IPostTypeDo {
return p.withDO(p.DO.Scopes(funcs...))
}
func (p postTypeDo) Unscoped() IPostTypeDo {
return p.withDO(p.DO.Unscoped())
}
func (p postTypeDo) Create(values ...*models.PostType) error {
if len(values) == 0 {
return nil
}
return p.DO.Create(values)
}
func (p postTypeDo) CreateInBatches(values []*models.PostType, batchSize int) error {
return p.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (p postTypeDo) Save(values ...*models.PostType) error {
if len(values) == 0 {
return nil
}
return p.DO.Save(values)
}
func (p postTypeDo) First() (*models.PostType, error) {
if result, err := p.DO.First(); err != nil {
return nil, err
} else {
return result.(*models.PostType), nil
}
}
func (p postTypeDo) Take() (*models.PostType, error) {
if result, err := p.DO.Take(); err != nil {
return nil, err
} else {
return result.(*models.PostType), nil
}
}
func (p postTypeDo) Last() (*models.PostType, error) {
if result, err := p.DO.Last(); err != nil {
return nil, err
} else {
return result.(*models.PostType), nil
}
}
func (p postTypeDo) Find() ([]*models.PostType, error) {
result, err := p.DO.Find()
return result.([]*models.PostType), err
}
func (p postTypeDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.PostType, err error) {
buf := make([]*models.PostType, 0, batchSize)
err = p.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (p postTypeDo) FindInBatches(result *[]*models.PostType, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return p.DO.FindInBatches(result, batchSize, fc)
}
func (p postTypeDo) Attrs(attrs ...field.AssignExpr) IPostTypeDo {
return p.withDO(p.DO.Attrs(attrs...))
}
func (p postTypeDo) Assign(attrs ...field.AssignExpr) IPostTypeDo {
return p.withDO(p.DO.Assign(attrs...))
}
func (p postTypeDo) Joins(fields ...field.RelationField) IPostTypeDo {
for _, _f := range fields {
p = *p.withDO(p.DO.Joins(_f))
}
return &p
}
func (p postTypeDo) Preload(fields ...field.RelationField) IPostTypeDo {
for _, _f := range fields {
p = *p.withDO(p.DO.Preload(_f))
}
return &p
}
func (p postTypeDo) FirstOrInit() (*models.PostType, error) {
if result, err := p.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*models.PostType), nil
}
}
func (p postTypeDo) FirstOrCreate() (*models.PostType, error) {
if result, err := p.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*models.PostType), nil
}
}
func (p postTypeDo) FindByPage(offset int, limit int) (result []*models.PostType, count int64, err error) {
result, err = p.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = p.Offset(-1).Limit(-1).Count()
return
}
func (p postTypeDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = p.Count()
if err != nil {
return
}
err = p.Offset(offset).Limit(limit).Scan(result)
return
}
func (p postTypeDo) Scan(result interface{}) (err error) {
return p.DO.Scan(result)
}
func (p postTypeDo) Delete(models ...*models.PostType) (result gen.ResultInfo, err error) {
return p.DO.Delete(models)
}
func (p *postTypeDo) withDO(do gen.Dao) *postTypeDo {
p.DO = *do.(*gen.DO)
return p
}

View File

@@ -0,0 +1,145 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package dal
import (
"app/internal/models"
"context"
"fmt"
"testing"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/gorm/clause"
)
func init() {
InitializeDB()
err := _gen_test_db.AutoMigrate(&models.PostType{})
if err != nil {
fmt.Printf("Error: AutoMigrate(&models.PostType{}) fail: %s", err)
}
}
func Test_postTypeQuery(t *testing.T) {
postType := newPostType(_gen_test_db)
postType = *postType.As(postType.TableName())
_do := postType.WithContext(context.Background()).Debug()
primaryKey := field.NewString(postType.TableName(), clause.PrimaryKey)
_, err := _do.Unscoped().Where(primaryKey.IsNotNull()).Delete()
if err != nil {
t.Error("clean table <post_types> fail:", err)
return
}
_, ok := postType.GetFieldByName("")
if ok {
t.Error("GetFieldByName(\"\") from postType success")
}
err = _do.Create(&models.PostType{})
if err != nil {
t.Error("create item in table <post_types> fail:", err)
}
err = _do.Save(&models.PostType{})
if err != nil {
t.Error("create item in table <post_types> fail:", err)
}
err = _do.CreateInBatches([]*models.PostType{{}, {}}, 10)
if err != nil {
t.Error("create item in table <post_types> fail:", err)
}
_, err = _do.Select(postType.ALL).Take()
if err != nil {
t.Error("Take() on table <post_types> fail:", err)
}
_, err = _do.First()
if err != nil {
t.Error("First() on table <post_types> fail:", err)
}
_, err = _do.Last()
if err != nil {
t.Error("First() on table <post_types> fail:", err)
}
_, err = _do.Where(primaryKey.IsNotNull()).FindInBatch(10, func(tx gen.Dao, batch int) error { return nil })
if err != nil {
t.Error("FindInBatch() on table <post_types> fail:", err)
}
err = _do.Where(primaryKey.IsNotNull()).FindInBatches(&[]*models.PostType{}, 10, func(tx gen.Dao, batch int) error { return nil })
if err != nil {
t.Error("FindInBatches() on table <post_types> fail:", err)
}
_, err = _do.Select(postType.ALL).Where(primaryKey.IsNotNull()).Order(primaryKey.Desc()).Find()
if err != nil {
t.Error("Find() on table <post_types> fail:", err)
}
_, err = _do.Distinct(primaryKey).Take()
if err != nil {
t.Error("select Distinct() on table <post_types> fail:", err)
}
_, err = _do.Select(postType.ALL).Omit(primaryKey).Take()
if err != nil {
t.Error("Omit() on table <post_types> fail:", err)
}
_, err = _do.Group(primaryKey).Find()
if err != nil {
t.Error("Group() on table <post_types> fail:", err)
}
_, err = _do.Scopes(func(dao gen.Dao) gen.Dao { return dao.Where(primaryKey.IsNotNull()) }).Find()
if err != nil {
t.Error("Scopes() on table <post_types> fail:", err)
}
_, _, err = _do.FindByPage(0, 1)
if err != nil {
t.Error("FindByPage() on table <post_types> fail:", err)
}
_, err = _do.ScanByPage(&models.PostType{}, 0, 1)
if err != nil {
t.Error("ScanByPage() on table <post_types> fail:", err)
}
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrInit()
if err != nil {
t.Error("FirstOrInit() on table <post_types> fail:", err)
}
_, err = _do.Attrs(primaryKey).Assign(primaryKey).FirstOrCreate()
if err != nil {
t.Error("FirstOrCreate() on table <post_types> fail:", err)
}
var _a _another
var _aPK = field.NewString(_a.TableName(), "id")
err = _do.Join(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
if err != nil {
t.Error("Join() on table <post_types> fail:", err)
}
err = _do.LeftJoin(&_a, primaryKey.EqCol(_aPK)).Scan(map[string]interface{}{})
if err != nil {
t.Error("LeftJoin() on table <post_types> fail:", err)
}
_, err = _do.Not().Or().Clauses().Take()
if err != nil {
t.Error("Not/Or/Clauses on table <post_types> fail:", err)
}
}

View File

@@ -31,6 +31,7 @@ func newPost(db *gorm.DB, opts ...gen.DOOption) post {
_post.Deadline = field.NewInt64(tableName, "deadline") _post.Deadline = field.NewInt64(tableName, "deadline")
_post.CreatedAt = field.NewInt64(tableName, "created_at") _post.CreatedAt = field.NewInt64(tableName, "created_at")
_post.AuthorId = field.NewUint(tableName, "author_id") _post.AuthorId = field.NewUint(tableName, "author_id")
_post.PostTypeId = field.NewUint(tableName, "post_type_id")
_post.Author = postBelongsToAuthor{ _post.Author = postBelongsToAuthor{
db: db.Session(&gorm.Session{}), db: db.Session(&gorm.Session{}),
@@ -40,6 +41,18 @@ func newPost(db *gorm.DB, opts ...gen.DOOption) post {
Author struct { Author struct {
field.RelationField field.RelationField
} }
PostType struct {
field.RelationField
}
Comments struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}
}{ }{
RelationField: field.NewRelation("Author.Posts", "models.Post"), RelationField: field.NewRelation("Author.Posts", "models.Post"),
Author: struct { Author: struct {
@@ -47,7 +60,50 @@ func newPost(db *gorm.DB, opts ...gen.DOOption) post {
}{ }{
RelationField: field.NewRelation("Author.Posts.Author", "models.Author"), RelationField: field.NewRelation("Author.Posts.Author", "models.Author"),
}, },
PostType: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Posts.PostType", "models.PostType"),
},
Comments: struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}{
RelationField: field.NewRelation("Author.Posts.Comments", "models.Comment"),
Author: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Posts.Comments.Author", "models.Author"),
},
Posts: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Posts.Comments.Posts", "models.Post"),
},
},
}, },
Comments: struct {
field.RelationField
}{
RelationField: field.NewRelation("Author.Comments", "models.Comment"),
},
}
_post.PostType = postBelongsToPostType{
db: db.Session(&gorm.Session{}),
RelationField: field.NewRelation("PostType", "models.PostType"),
}
_post.Comments = postManyToManyComments{
db: db.Session(&gorm.Session{}),
RelationField: field.NewRelation("Comments", "models.Comment"),
} }
_post.fillFieldMap() _post.fillFieldMap()
@@ -58,13 +114,18 @@ func newPost(db *gorm.DB, opts ...gen.DOOption) post {
type post struct { type post struct {
postDo postDo
ALL field.Asterisk ALL field.Asterisk
Id field.Uint Id field.Uint
Text field.String Text field.String
Deadline field.Int64 Deadline field.Int64
CreatedAt field.Int64 CreatedAt field.Int64
AuthorId field.Uint AuthorId field.Uint
Author postBelongsToAuthor PostTypeId field.Uint
Author postBelongsToAuthor
PostType postBelongsToPostType
Comments postManyToManyComments
fieldMap map[string]field.Expr fieldMap map[string]field.Expr
} }
@@ -86,6 +147,7 @@ func (p *post) updateTableName(table string) *post {
p.Deadline = field.NewInt64(table, "deadline") p.Deadline = field.NewInt64(table, "deadline")
p.CreatedAt = field.NewInt64(table, "created_at") p.CreatedAt = field.NewInt64(table, "created_at")
p.AuthorId = field.NewUint(table, "author_id") p.AuthorId = field.NewUint(table, "author_id")
p.PostTypeId = field.NewUint(table, "post_type_id")
p.fillFieldMap() p.fillFieldMap()
@@ -102,12 +164,13 @@ func (p *post) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
} }
func (p *post) fillFieldMap() { func (p *post) fillFieldMap() {
p.fieldMap = make(map[string]field.Expr, 6) p.fieldMap = make(map[string]field.Expr, 9)
p.fieldMap["id"] = p.Id p.fieldMap["id"] = p.Id
p.fieldMap["text"] = p.Text p.fieldMap["text"] = p.Text
p.fieldMap["deadline"] = p.Deadline p.fieldMap["deadline"] = p.Deadline
p.fieldMap["created_at"] = p.CreatedAt p.fieldMap["created_at"] = p.CreatedAt
p.fieldMap["author_id"] = p.AuthorId p.fieldMap["author_id"] = p.AuthorId
p.fieldMap["post_type_id"] = p.PostTypeId
} }
@@ -131,6 +194,21 @@ type postBelongsToAuthor struct {
Author struct { Author struct {
field.RelationField field.RelationField
} }
PostType struct {
field.RelationField
}
Comments struct {
field.RelationField
Author struct {
field.RelationField
}
Posts struct {
field.RelationField
}
}
}
Comments struct {
field.RelationField
} }
} }
@@ -199,6 +277,148 @@ func (a postBelongsToAuthorTx) Count() int64 {
return a.tx.Count() return a.tx.Count()
} }
type postBelongsToPostType struct {
db *gorm.DB
field.RelationField
}
func (a postBelongsToPostType) Where(conds ...field.Expr) *postBelongsToPostType {
if len(conds) == 0 {
return &a
}
exprs := make([]clause.Expression, 0, len(conds))
for _, cond := range conds {
exprs = append(exprs, cond.BeCond().(clause.Expression))
}
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
return &a
}
func (a postBelongsToPostType) WithContext(ctx context.Context) *postBelongsToPostType {
a.db = a.db.WithContext(ctx)
return &a
}
func (a postBelongsToPostType) Session(session *gorm.Session) *postBelongsToPostType {
a.db = a.db.Session(session)
return &a
}
func (a postBelongsToPostType) Model(m *models.Post) *postBelongsToPostTypeTx {
return &postBelongsToPostTypeTx{a.db.Model(m).Association(a.Name())}
}
type postBelongsToPostTypeTx struct{ tx *gorm.Association }
func (a postBelongsToPostTypeTx) Find() (result *models.PostType, err error) {
return result, a.tx.Find(&result)
}
func (a postBelongsToPostTypeTx) Append(values ...*models.PostType) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Append(targetValues...)
}
func (a postBelongsToPostTypeTx) Replace(values ...*models.PostType) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Replace(targetValues...)
}
func (a postBelongsToPostTypeTx) Delete(values ...*models.PostType) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Delete(targetValues...)
}
func (a postBelongsToPostTypeTx) Clear() error {
return a.tx.Clear()
}
func (a postBelongsToPostTypeTx) Count() int64 {
return a.tx.Count()
}
type postManyToManyComments struct {
db *gorm.DB
field.RelationField
}
func (a postManyToManyComments) Where(conds ...field.Expr) *postManyToManyComments {
if len(conds) == 0 {
return &a
}
exprs := make([]clause.Expression, 0, len(conds))
for _, cond := range conds {
exprs = append(exprs, cond.BeCond().(clause.Expression))
}
a.db = a.db.Clauses(clause.Where{Exprs: exprs})
return &a
}
func (a postManyToManyComments) WithContext(ctx context.Context) *postManyToManyComments {
a.db = a.db.WithContext(ctx)
return &a
}
func (a postManyToManyComments) Session(session *gorm.Session) *postManyToManyComments {
a.db = a.db.Session(session)
return &a
}
func (a postManyToManyComments) Model(m *models.Post) *postManyToManyCommentsTx {
return &postManyToManyCommentsTx{a.db.Model(m).Association(a.Name())}
}
type postManyToManyCommentsTx struct{ tx *gorm.Association }
func (a postManyToManyCommentsTx) Find() (result []*models.Comment, err error) {
return result, a.tx.Find(&result)
}
func (a postManyToManyCommentsTx) Append(values ...*models.Comment) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Append(targetValues...)
}
func (a postManyToManyCommentsTx) Replace(values ...*models.Comment) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Replace(targetValues...)
}
func (a postManyToManyCommentsTx) Delete(values ...*models.Comment) (err error) {
targetValues := make([]interface{}, len(values))
for i, v := range values {
targetValues[i] = v
}
return a.tx.Delete(targetValues...)
}
func (a postManyToManyCommentsTx) Clear() error {
return a.tx.Clear()
}
func (a postManyToManyCommentsTx) Count() int64 {
return a.tx.Count()
}
type postDo struct{ gen.DO } type postDo struct{ gen.DO }
type IPostDo interface { type IPostDo interface {

View File

@@ -1,7 +1,7 @@
package models package models
var Entities = []any{ var Entities = []any{
&Post{}, &Author{}, &PostType{}, &Post{}, &Author{}, &PostType{}, &Comment{},
} }
type PostType struct { type PostType struct {
@@ -10,18 +10,28 @@ type PostType struct {
} }
type Post struct { type Post struct {
Id uint `gorm:"primaryKey" ui:"hidden"` Id uint `gorm:"primaryKey" ui:"hidden"`
Text string `displayName:"Текст" ui:"label:Текст"` Text string `ui:"label:Текст"`
Deadline int64 `ui:"label:Дедлайн;datatype:datetime;"` Deadline int64 `ui:"label:Дедлайн;datatype:datetime;"`
CreatedAt int64 `gorm:"autoCreateTime" ui:"readonly;datatype:datetime;"` CreatedAt int64 `gorm:"autoCreateTime" ui:"readonly;datatype:datetime;"`
AuthorId uint `ui:"hidden" gorm:"foreignKey:Id;references:AuthorId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"` AuthorId uint `ui:"hidden" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
Author Author `ui:"label:Автор; field:Name;"` Author Author `ui:"label:Автор; field:Name;"`
TypeId uint `ui:"hidden"` PostTypeId uint `ui:"hidden"`
PostType PostType `ui:"label:Тип; field:Name;" gorm:"foreignKey:Id;references:TypeId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"` PostType PostType `ui:"label:Тип; field:Name;" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
Comments []Comment `ui:"label:Комментарии; field:Text;" gorm:"many2many:comments_post;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
} }
type Author struct { type Author struct {
Id uint `gorm:"primaryKey" ui:"hidden"` Id uint `gorm:"primaryKey" ui:"hidden"`
Name string `ui:"label:Имя;"` Name string `ui:"label:Имя;"`
Posts []Post `ui:"label:Посты; field:Text;" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"` Posts []Post `ui:"label:Посты; field:Text;" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
Comments []Comment `ui:"label:Комментарии; field:Text;" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}
type Comment struct {
Id uint `gorm:"primaryKey" ui:"hidden"`
Text string `ui:"label:Текст;"`
AuthorId uint `ui:"hidden"`
Author Author `ui:"label:Автор; field:Name;" gorm:"foreignKey:Id;references:AuthorId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
Posts []Post `ui:"label:Посты; field:Text;" gorm:"many2many:comments_post;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
} }

View File

@@ -0,0 +1,66 @@
package services
import (
"app/internal/dal"
"app/internal/database"
"app/internal/models"
"errors"
"gorm.io/gen/field"
"gorm.io/gorm"
)
type CommentService struct {
}
type Comment = models.Comment
func (service *CommentService) Create(item Comment) (Comment, error) {
ReplaceEmptySlicesWithNil(&item)
err := dal.Comment.Preload(field.Associations).Create(&item)
if err != nil {
return item, err
}
err = AppendAssociations(database.GetInstance(), &item)
return item, err
}
func (service *CommentService) GetAll() ([]*Comment, error) {
var comments []*Comment
comments, err := dal.Comment.Preload(field.Associations).Find()
return comments, err
}
func (service *CommentService) GetById(id uint) (*Comment, error) {
item, err := dal.Comment.Preload(field.Associations).Where(dal.Comment.Id.Eq(id)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
} else {
return nil, err
}
}
return item, nil
}
func (service *CommentService) Update(item Comment) (Comment, error) {
ReplaceEmptySlicesWithNil(&item)
err := dal.Comment.Preload(field.Associations).Save(&item)
if err != nil {
return item, err
}
err = UpdateAssociations(database.GetInstance(), &item)
if err != nil {
return item, err
}
return item, err
}
func (service *CommentService) Delete(id uint) error {
_, err := dal.Comment.Unscoped().Where(dal.Comment.Id.Eq(id)).Delete()
return err
}
func (service *CommentService) Count() (int64, error) {
amount, err := dal.Comment.Count()
return amount, err
}

View File

@@ -7,8 +7,10 @@ import (
) )
func InsertDefaultData() { func InsertDefaultData() {
insertPostTypes()
insertAuthors() insertAuthors()
insertPosts() insertPosts()
insertComments()
} }
func InsertDefaultEntityData[T any](service Service[T], entities []T) { func InsertDefaultEntityData[T any](service Service[T], entities []T) {
@@ -23,22 +25,25 @@ func InsertDefaultEntityData[T any](service Service[T], entities []T) {
func insertPosts() { func insertPosts() {
InsertDefaultEntityData(&PostService{}, []Post{ InsertDefaultEntityData(&PostService{}, []Post{
{ {
Id: 1, Id: 1,
Text: "Жителям Кузбасса запретили болеть.", Text: "Жителям Кузбасса запретили болеть.",
Deadline: time.Now().Unix(), Deadline: time.Now().Unix(),
AuthorId: 1, AuthorId: 1,
PostTypeId: 1,
}, },
{ {
Id: 2, Id: 2,
Deadline: time.Now().Add(time.Hour * 24 * 5).Unix(), Deadline: time.Now().Add(time.Hour * 24 * 5).Unix(),
Text: "⚡️⚡️⚡️Дома будут летать.", Text: "⚡️⚡️⚡️Дома будут летать.",
AuthorId: 2, AuthorId: 2,
PostTypeId: 2,
}, },
{ {
Id: 3, Id: 3,
Deadline: time.Now().Add(time.Hour * 24 * 6).Unix(), Deadline: time.Now().Add(time.Hour * 24 * 6).Unix(),
Text: "В Кузбассе начали строить дома выше, чтобы жители были ближе к богу и солнцу.", Text: "В Кузбассе начали строить дома выше, чтобы жители были ближе к богу и солнцу.",
AuthorId: 3, AuthorId: 3,
PostTypeId: 3,
}, },
}) })
} }
@@ -59,3 +64,43 @@ func insertAuthors() {
}, },
}) })
} }
func insertComments() {
InsertDefaultEntityData(&CommentService{}, []Comment{
{
Id: 1,
Text: "Это просто замечательно!",
AuthorId: 1,
Posts: []Post{{Id: 1}},
},
{
Id: 2,
Text: "Я тоже думаю, что это замечательно!",
AuthorId: 2,
Posts: []Post{{Id: 2}},
},
{
Id: 3,
Text: "Я тоже думаю, что это замечательно!",
AuthorId: 3,
Posts: []Post{{Id: 3}},
},
})
}
func insertPostTypes() {
InsertDefaultEntityData(&PostTypeService{}, []PostType{
{
Id: 1,
Name: "Общество",
},
{
Id: 2,
Name: "Политика",
},
{
Id: 3,
Name: "Экономика",
},
})
}

View File

@@ -2,11 +2,13 @@ package services
import ( import (
"app/internal/dal" "app/internal/dal"
"app/internal/database"
"app/internal/dialogs" "app/internal/dialogs"
excel "app/internal/extras/excel" excel "app/internal/extras/excel"
"app/internal/models" "app/internal/models"
"errors" "errors"
"fmt" "fmt"
"gorm.io/gen/field" "gorm.io/gen/field"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -15,7 +17,12 @@ type PostService struct{}
type Post = models.Post type Post = models.Post
func (service *PostService) Create(item Post) (Post, error) { func (service *PostService) Create(item Post) (Post, error) {
ReplaceEmptySlicesWithNil(&item)
err := dal.Post.Preload(field.Associations).Create(&item) err := dal.Post.Preload(field.Associations).Create(&item)
if err != nil {
return item, err
}
err = AppendAssociations(database.GetInstance(), &item)
return item, err return item, err
} }
func (service *PostService) GetAll() ([]*Post, error) { func (service *PostService) GetAll() ([]*Post, error) {
@@ -34,10 +41,20 @@ func (service *PostService) GetById(id uint) (*Post, error) {
} }
return item, nil return item, nil
} }
func (service *PostService) Update(item Post) (Post, error) { func (service *PostService) Update(item Post) (Post, error) {
ReplaceEmptySlicesWithNil(&item)
err := dal.Post.Preload(field.Associations).Save(&item) err := dal.Post.Preload(field.Associations).Save(&item)
if err != nil {
return item, err
}
err = UpdateAssociations(database.GetInstance(), &item)
if err != nil {
return item, err
}
return item, err return item, err
} }
func (service *PostService) Delete(id uint) error { func (service *PostService) Delete(id uint) error {
_, err := dal.Post.Unscoped().Where(dal.Post.Id.Eq(id)).Delete() _, err := dal.Post.Unscoped().Where(dal.Post.Id.Eq(id)).Delete()
return err return err

View File

@@ -0,0 +1,61 @@
package services
import (
"app/internal/dal"
"app/internal/database"
"app/internal/models"
"errors"
"gorm.io/gen/field"
"gorm.io/gorm"
)
type PostTypeService struct {
}
type PostType = models.PostType
func (service *PostTypeService) Create(item PostType) (PostType, error) {
ReplaceEmptySlicesWithNil(&item)
err := dal.PostType.Preload(field.Associations).Create(&item)
if err != nil {
return item, err
}
err = AppendAssociations(database.GetInstance(), &item)
return item, err
}
func (service *PostTypeService) GetAll() ([]*PostType, error) {
var posttypes []*PostType
posttypes, err := dal.PostType.Preload(field.Associations).Find()
return posttypes, err
}
func (service *PostTypeService) GetById(id uint) (*PostType, error) {
item, err := dal.PostType.Preload(field.Associations).Where(dal.PostType.Id.Eq(id)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
} else {
return nil, err
}
}
return item, nil
}
func (service *PostTypeService) Update(item PostType) (PostType, error) {
ReplaceEmptySlicesWithNil(&item)
err := dal.PostType.Preload(field.Associations).Save(&item)
if err != nil {
return item, err
}
err = UpdateAssociations(database.GetInstance(), &item)
if err != nil {
return item, err
}
return item, err
}
func (service *PostTypeService) Delete(id uint) error {
_, err := dal.PostType.Unscoped().Where(dal.PostType.Id.Eq(id)).Delete()
return err
}
func (service *PostTypeService) Count() (int64, error) {
amount, err := dal.PostType.Count()
return amount, err
}

View File

@@ -5,4 +5,6 @@ import "github.com/wailsapp/wails/v3/pkg/application"
var ExportedServices = []application.Service{ var ExportedServices = []application.Service{
application.NewService(&PostService{}), application.NewService(&PostService{}),
application.NewService(&AuthorService{}), application.NewService(&AuthorService{}),
application.NewService(&CommentService{}),
application.NewService(&PostTypeService{}),
} }