Code Monkey home page Code Monkey logo

Comments (6)

gwynne avatar gwynne commented on May 29, 2024 1

This should work if you use @Enum(key:) rather than @Field(key:)

from fluent-kit.

gwynne avatar gwynne commented on May 29, 2024 1

Okay, so it turns out this is indeed a FluentKit bug - we test with @Enum, but not @OptionalEnum. As soon as I added a test for the latter, it failed. I'll see if I can push a fix for this tonight!

from fluent-kit.

Frizlab avatar Frizlab commented on May 29, 2024

My bad, I (sadly) did my code right; I just failed when creating the snippet for the bug report.
The actual definition of the sex property in my model is like so: @OptionalEnum(key: FieldKeys.sex)

from fluent-kit.

gwynne avatar gwynne commented on May 29, 2024

Can you show your migration? We have tests for this in the FluentBenchmarks test suite, so it's odd that it wouldn't be working for you.

from fluent-kit.

Frizlab avatar Frizlab commented on May 29, 2024

Yes sure.
I’ll give even more details as I can see the problem seems not trivial.

My situation is not exactly like I said initially as the filter is done for a JOINed entity. Maybe the problem is there.

I have a User entity and a ConsumerProfile entity whose ID is a foreign key to User.
The sex is a part of the User (everybody has a sex; not only the consumers).
I do a query on the ConsumerProfile and join it to User to only get the consumers of a given sex, where sexes is a Set of Sex:

consumersQuery
	.join(parent: \.$id.$user)
	.filter(DbUser.self, \.$sex ~~ sexes)

Sex enum migration

struct CreateSexEnum : AsyncMigration {
	
	static let enumName = "sex"
	
	func prepare(on database: Database) async throws {
		assert(Self.enumName.utf8CString.count <= Self.maxAllowedTableNameLength)
		_ = try await database.enum(Self.enumName)
			.case(Sex.male.rawValue)
			.case(Sex.female.rawValue)
			.create()
	}
	
	func revert(on database: Database) async throws {
		try await database.enum(Self.enumName).delete()
	}
	
}

User model and migration

final class DbUser : Model {
	
	static let schema = "users"
	
	@ID
	var id: UUID?
	
	@Timestamp(key: FieldKeys.createdAt, on: .create)
	var createdAt: Date?
	
	@Timestamp(key: FieldKeys.updatedAt, on: .update)
	var updatedAt: Date?
	
	@Field(key: FieldKeys.firstName)
	var firstName: String
	
	@OptionalEnum(key: FieldKeys.sex)
	var sex: Sex?
	
	@OptionalChild(for: \.$id.$user)
	var i_consumerProfile: DbConsumerProfile?
	
	/* *******
	   MARK: -
	   ******* */
	
	enum FieldKeys {
		
		static let createdAt: FieldKey = "created_at"
		static let updatedAt: FieldKey = "updated_at"
		
		static let firstName: FieldKey = "first_name"
		static let sex: FieldKey = "sex"
		
	}
	
}

struct CreateUsersTable : AsyncMigration {
	
	typealias Table = DbUser
	typealias Keys = Table.FieldKeys
	
	func prepare(on database: Database) async throws {
		assert(Table.schema.utf8CString.count <= Self.maxAllowedTableNameLength)
		let sexEnum = try await database.enum(CreateSexEnum.enumName).read()
		try await database.schema(Table.schema)
			.id()
			.field(Keys.createdAt,          .datetime, .required)
			.field(Keys.updatedAt,          .datetime, .required)
			.field(Keys.firstName,          .string,   .required)
->			.field(Keys.sex,                 sexEnum)
			…
			.unique(on: .id)
			.create()
	}
	
	func revert(on database: Database) async throws {
		try await database.schema(Table.schema).delete()
	}
	
}

ConsumerProfile model and migration

final class DbConsumerProfile : Model {
	
	static let schema = "consumer_profiles"
	
	final class IDValue : Fields, Hashable {
		
		@Parent(key: FieldKeys.userID)
		var user: DbUser
		
		init() {}
		
		init(_ userID: UUID) {
			self.$user.id = userID
		}
		
		init(user: DbUser) throws {
			self.$user.id = try user.requireID()
			self.$user.value = user
		}
		
		func duplicate() -> Self {
			return .init($user.id)
		}
		
		public static func ==(lhs: IDValue, rhs: IDValue) -> Bool {
			lhs.$user.id == rhs.$user.id
		}
		
		public func hash(into hasher: inout Hasher) {
			hasher.combine($user.id)
		}
		
	}
	
	@CompositeID()
	var id: IDValue?
	var user: DbUser? {id?.user}
	func requireUserID() throws -> UUID {
		return try requireID().$user.id
	}
	func setUser(_ dbUser: DbUser) throws {
		id = try .init(user: dbUser)
	}
	
	@Timestamp(key: FieldKeys.createdAt, on: .create)
	var createdAt: Date?
	
	@Timestamp(key: FieldKeys.updatedAt, on: .update)
	var updatedAt: Date?
	
	enum FieldKeys {
		
		static let userID: FieldKey = "user_id"
		
		static let createdAt: FieldKey = DbUser.FieldKeys.createdAt
		static let updatedAt: FieldKey = DbUser.FieldKeys.updatedAt
		
	}
	
}

struct CreateConsumerProfilesTable : AsyncMigration {
	
	typealias Table = DbConsumerProfile
	typealias Keys = Table.FieldKeys
	
	func prepare(on database: Database) async throws {
		assert(Table.schema.utf8CString.count <= Self.maxAllowedTableNameLength)
		try await database.schema(Table.schema)
			.field(Keys.userID,                          .uuid,     .required, .references(DbUser.schema,    FieldKey.id, onDelete: .cascade), .identifier(auto: false))
			.field(Keys.createdAt,                       .datetime, .required)
			.field(Keys.updatedAt,                       .datetime, .required)
			.unique(on: Keys.userID)
			.create()
	}
	
	func revert(on database: Database) async throws {
		try await database.schema(Table.schema).delete()
	}
	
}

from fluent-kit.

Frizlab avatar Frizlab commented on May 29, 2024

It works now, with the update you’ve just released. Thanks!

from fluent-kit.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.