From 75169c9d7efc18763a4c61a0969a1f1cc9ab6c47 Mon Sep 17 00:00:00 2001 From: Simon Binder Date: Sun, 23 Oct 2022 17:15:59 +0200 Subject: [PATCH] Read type converters in drift files --- drift/test/generated/custom_tables.g.dart | 2651 ++++++++++++----- drift/test/generated/todos.g.dart | 21 +- drift_dev/lib/src/analysis/backend.dart | 22 + .../src/analysis/resolver/drift/query.dart | 6 + .../src/analysis/resolver/drift/table.dart | 73 +- drift_dev/lib/src/analysis/results/query.dart | 7 + drift_dev/lib/src/analysis/serializer.dart | 2 + drift_dev/lib/src/backends/build/backend.dart | 39 + .../lib/src/backends/build/drift_builder.dart | 33 +- drift_dev/lib/src/writer/database_writer.dart | 37 +- .../lib/src/writer/drift_accessor_writer.dart | 34 + .../lib/src/writer/tables/view_writer.dart | 1 + 12 files changed, 2211 insertions(+), 715 deletions(-) create mode 100644 drift_dev/lib/src/writer/drift_accessor_writer.dart diff --git a/drift/test/generated/custom_tables.g.dart b/drift/test/generated/custom_tables.g.dart index b8757661..a02f1d9f 100644 --- a/drift/test/generated/custom_tables.g.dart +++ b/drift/test/generated/custom_tables.g.dart @@ -3,726 +3,2001 @@ part of 'custom_tables.dart'; class NoIdsCompanion extends UpdateCompanion { -final Value payload; -const NoIdsCompanion({this.payload = const Value.absent(),}); -NoIdsCompanion.insert({required Uint8List payload,}): payload = Value(payload); -static Insertable custom({Expression? payload, -}) { -return RawValuesInsertable({if (payload != null)'payload': payload,}); -}NoIdsCompanion copyWith({Value? payload}) { -return NoIdsCompanion(payload: payload ?? this.payload,); -} -@override -Map toColumns(bool nullToAbsent) { -final map = {};if (payload.present) {map['payload'] = Variable(payload.value);}return map; -} -@override -String toString() {return (StringBuffer('NoIdsCompanion(')..write('payload: $payload')..write(')')).toString();} + final Value payload; + const NoIdsCompanion({ + this.payload = const Value.absent(), + }); + NoIdsCompanion.insert({ + required Uint8List payload, + }) : payload = Value(payload); + static Insertable custom({ + Expression? payload, + }) { + return RawValuesInsertable({ + if (payload != null) 'payload': payload, + }); + } + + NoIdsCompanion copyWith({Value? payload}) { + return NoIdsCompanion( + payload: payload ?? this.payload, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (payload.present) { + map['payload'] = Variable(payload.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('NoIdsCompanion(') + ..write('payload: $payload') + ..write(')')) + .toString(); + } } + class $NoIdsTable extends Table with TableInfo<$NoIdsTable, NoIdRow> { -@override final GeneratedDatabase attachedDatabase; -final String? _alias; -$NoIdsTable(this.attachedDatabase, [this._alias]); -final VerificationMeta _payloadMeta = const VerificationMeta('payload'); -late final GeneratedColumn payload = GeneratedColumn('payload', aliasedName, false, type: DriftSqlType.blob, requiredDuringInsert: true); -@override -List get $columns => [payload]; -@override -String get aliasedName => _alias ?? 'no_ids'; -@override - String get actualTableName => 'no_ids'; -@override -VerificationContext validateIntegrity(Insertable instance, {bool isInserting = false}) { -final context = VerificationContext(); -final data = instance.toColumns(true); -if (data.containsKey('payload')) { -context.handle(_payloadMeta, payload.isAcceptableOrUnknown(data['payload']!, _payloadMeta));} else if (isInserting) { -context.missing(_payloadMeta); + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $NoIdsTable(this.attachedDatabase, [this._alias]); + final VerificationMeta _payloadMeta = const VerificationMeta('payload'); + late final GeneratedColumn payload = GeneratedColumn( + 'payload', aliasedName, false, + type: DriftSqlType.blob, requiredDuringInsert: true); + @override + List get $columns => [payload]; + @override + String get aliasedName => _alias ?? 'no_ids'; + @override + String get actualTableName => 'no_ids'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('payload')) { + context.handle(_payloadMeta, + payload.isAcceptableOrUnknown(data['payload']!, _payloadMeta)); + } else if (isInserting) { + context.missing(_payloadMeta); + } + return context; + } + + @override + Set get $primaryKey => const {}; + @override + NoIdRow map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return NoIdRow( + attachedDatabase.options.types + .read(DriftSqlType.blob, data['${effectivePrefix}payload'])!, + ); + } + + @override + $NoIdsTable createAlias(String alias) { + return $NoIdsTable(attachedDatabase, alias); + } + + @override + bool get withoutRowId => true; } -return context; + +class WithDefault extends DataClass implements Insertable { + final String? a; + final int? b; + const WithDefault({this.a, this.b}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (!nullToAbsent || a != null) { + map['a'] = Variable(a); + } + if (!nullToAbsent || b != null) { + map['b'] = Variable(b); + } + return map; + } + + WithDefaultsCompanion toCompanion(bool nullToAbsent) { + return WithDefaultsCompanion( + a: a == null && nullToAbsent ? const Value.absent() : Value(a), + b: b == null && nullToAbsent ? const Value.absent() : Value(b), + ); + } + + factory WithDefault.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return WithDefault( + a: serializer.fromJson(json['a']), + b: serializer.fromJson(json['b']), + ); + } + factory WithDefault.fromJsonString(String encodedJson, + {ValueSerializer? serializer}) => + WithDefault.fromJson( + DataClass.parseJson(encodedJson) as Map, + serializer: serializer); + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'a': serializer.toJson(a), + 'b': serializer.toJson(b), + }; + } + + WithDefault copyWith( + {Value a = const Value.absent(), + Value b = const Value.absent()}) => + WithDefault( + a: a.present ? a.value : this.a, + b: b.present ? b.value : this.b, + ); + @override + String toString() { + return (StringBuffer('WithDefault(') + ..write('a: $a, ') + ..write('b: $b') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(a, b); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is WithDefault && other.a == this.a && other.b == this.b); } -@override -Set get $primaryKey => const {};@override NoIdRow map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return NoIdRow(attachedDatabase.options.types.read(DriftSqlType.blob, data['${effectivePrefix}payload'])!, ); + +class WithDefaultsCompanion extends UpdateCompanion { + final Value a; + final Value b; + const WithDefaultsCompanion({ + this.a = const Value.absent(), + this.b = const Value.absent(), + }); + WithDefaultsCompanion.insert({ + this.a = const Value.absent(), + this.b = const Value.absent(), + }); + static Insertable custom({ + Expression? a, + Expression? b, + }) { + return RawValuesInsertable({ + if (a != null) 'a': a, + if (b != null) 'b': b, + }); + } + + WithDefaultsCompanion copyWith({Value? a, Value? b}) { + return WithDefaultsCompanion( + a: a ?? this.a, + b: b ?? this.b, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (a.present) { + map['a'] = Variable(a.value); + } + if (b.present) { + map['b'] = Variable(b.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('WithDefaultsCompanion(') + ..write('a: $a, ') + ..write('b: $b') + ..write(')')) + .toString(); + } } -@override -$NoIdsTable createAlias(String alias) { -return $NoIdsTable(attachedDatabase, alias);}@override -bool get withoutRowId => true; -}class WithDefault extends DataClass implements Insertable { -final String? a; -final int? b; -const WithDefault({this.a, this.b});@override -Map toColumns(bool nullToAbsent) { -final map = {};if (!nullToAbsent || a != null){map['a'] = Variable(a);}if (!nullToAbsent || b != null){map['b'] = Variable(b);}return map; + +class $WithDefaultsTable extends Table + with TableInfo<$WithDefaultsTable, WithDefault> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $WithDefaultsTable(this.attachedDatabase, [this._alias]); + final VerificationMeta _aMeta = const VerificationMeta('a'); + late final GeneratedColumn a = GeneratedColumn( + 'a', aliasedName, true, + type: DriftSqlType.string, requiredDuringInsert: false); + final VerificationMeta _bMeta = const VerificationMeta('b'); + late final GeneratedColumn b = GeneratedColumn( + 'b', aliasedName, true, + type: DriftSqlType.int, requiredDuringInsert: false); + @override + List get $columns => [a, b]; + @override + String get aliasedName => _alias ?? 'with_defaults'; + @override + String get actualTableName => 'with_defaults'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('a')) { + context.handle(_aMeta, a.isAcceptableOrUnknown(data['a']!, _aMeta)); + } + if (data.containsKey('b')) { + context.handle(_bMeta, b.isAcceptableOrUnknown(data['b']!, _bMeta)); + } + return context; + } + + @override + Set get $primaryKey => const {}; + @override + WithDefault map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return WithDefault( + a: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}a']), + b: attachedDatabase.options.types + .read(DriftSqlType.int, data['${effectivePrefix}b']), + ); + } + + @override + $WithDefaultsTable createAlias(String alias) { + return $WithDefaultsTable(attachedDatabase, alias); + } } -WithDefaultsCompanion toCompanion(bool nullToAbsent) { -return WithDefaultsCompanion(a: a == null && nullToAbsent ? const Value.absent() : Value (a),b: b == null && nullToAbsent ? const Value.absent() : Value (b),); + +class WithConstraint extends DataClass implements Insertable { + final String? a; + final int b; + final double? c; + const WithConstraint({this.a, required this.b, this.c}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (!nullToAbsent || a != null) { + map['a'] = Variable(a); + } + map['b'] = Variable(b); + if (!nullToAbsent || c != null) { + map['c'] = Variable(c); + } + return map; + } + + WithConstraintsCompanion toCompanion(bool nullToAbsent) { + return WithConstraintsCompanion( + a: a == null && nullToAbsent ? const Value.absent() : Value(a), + b: Value(b), + c: c == null && nullToAbsent ? const Value.absent() : Value(c), + ); + } + + factory WithConstraint.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return WithConstraint( + a: serializer.fromJson(json['a']), + b: serializer.fromJson(json['b']), + c: serializer.fromJson(json['c']), + ); + } + factory WithConstraint.fromJsonString(String encodedJson, + {ValueSerializer? serializer}) => + WithConstraint.fromJson( + DataClass.parseJson(encodedJson) as Map, + serializer: serializer); + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'a': serializer.toJson(a), + 'b': serializer.toJson(b), + 'c': serializer.toJson(c), + }; + } + + WithConstraint copyWith( + {Value a = const Value.absent(), + int? b, + Value c = const Value.absent()}) => + WithConstraint( + a: a.present ? a.value : this.a, + b: b ?? this.b, + c: c.present ? c.value : this.c, + ); + @override + String toString() { + return (StringBuffer('WithConstraint(') + ..write('a: $a, ') + ..write('b: $b, ') + ..write('c: $c') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(a, b, c); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is WithConstraint && + other.a == this.a && + other.b == this.b && + other.c == this.c); } -factory WithDefault.fromJson(Map json, {ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return WithDefault(a: serializer.fromJson(json['a']),b: serializer.fromJson(json['b']),);} -factory WithDefault.fromJsonString(String encodedJson, {ValueSerializer? serializer}) => WithDefault.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer);@override Map toJson({ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return { -'a': serializer.toJson(a),'b': serializer.toJson(b),};}WithDefault copyWith({Value a = const Value.absent(),Value b = const Value.absent()}) => WithDefault(a: a.present ? a.value : this.a,b: b.present ? b.value : this.b,);@override -String toString() {return (StringBuffer('WithDefault(')..write('a: $a, ')..write('b: $b')..write(')')).toString();} -@override - int get hashCode => Object.hash(a, b);@override -bool operator ==(Object other) => identical(this, other) || (other is WithDefault && other.a == this.a && other.b == this.b); -}class WithDefaultsCompanion extends UpdateCompanion { -final Value a; -final Value b; -const WithDefaultsCompanion({this.a = const Value.absent(),this.b = const Value.absent(),}); -WithDefaultsCompanion.insert({this.a = const Value.absent(),this.b = const Value.absent(),}); -static Insertable custom({Expression? a, -Expression? b, -}) { -return RawValuesInsertable({if (a != null)'a': a,if (b != null)'b': b,}); -}WithDefaultsCompanion copyWith({Value? a, Value? b}) { -return WithDefaultsCompanion(a: a ?? this.a,b: b ?? this.b,); + +class WithConstraintsCompanion extends UpdateCompanion { + final Value a; + final Value b; + final Value c; + const WithConstraintsCompanion({ + this.a = const Value.absent(), + this.b = const Value.absent(), + this.c = const Value.absent(), + }); + WithConstraintsCompanion.insert({ + this.a = const Value.absent(), + required int b, + this.c = const Value.absent(), + }) : b = Value(b); + static Insertable custom({ + Expression? a, + Expression? b, + Expression? c, + }) { + return RawValuesInsertable({ + if (a != null) 'a': a, + if (b != null) 'b': b, + if (c != null) 'c': c, + }); + } + + WithConstraintsCompanion copyWith( + {Value? a, Value? b, Value? c}) { + return WithConstraintsCompanion( + a: a ?? this.a, + b: b ?? this.b, + c: c ?? this.c, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (a.present) { + map['a'] = Variable(a.value); + } + if (b.present) { + map['b'] = Variable(b.value); + } + if (c.present) { + map['c'] = Variable(c.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('WithConstraintsCompanion(') + ..write('a: $a, ') + ..write('b: $b, ') + ..write('c: $c') + ..write(')')) + .toString(); + } } -@override -Map toColumns(bool nullToAbsent) { -final map = {};if (a.present) {map['a'] = Variable(a.value);}if (b.present) {map['b'] = Variable(b.value);}return map; + +class $WithConstraintsTable extends Table + with TableInfo<$WithConstraintsTable, WithConstraint> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $WithConstraintsTable(this.attachedDatabase, [this._alias]); + final VerificationMeta _aMeta = const VerificationMeta('a'); + late final GeneratedColumn a = GeneratedColumn( + 'a', aliasedName, true, + type: DriftSqlType.string, requiredDuringInsert: false); + final VerificationMeta _bMeta = const VerificationMeta('b'); + late final GeneratedColumn b = GeneratedColumn( + 'b', aliasedName, false, + type: DriftSqlType.int, requiredDuringInsert: true); + final VerificationMeta _cMeta = const VerificationMeta('c'); + late final GeneratedColumn c = GeneratedColumn( + 'c', aliasedName, true, + type: DriftSqlType.double, requiredDuringInsert: false); + @override + List get $columns => [a, b, c]; + @override + String get aliasedName => _alias ?? 'with_constraints'; + @override + String get actualTableName => 'with_constraints'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('a')) { + context.handle(_aMeta, a.isAcceptableOrUnknown(data['a']!, _aMeta)); + } + if (data.containsKey('b')) { + context.handle(_bMeta, b.isAcceptableOrUnknown(data['b']!, _bMeta)); + } else if (isInserting) { + context.missing(_bMeta); + } + if (data.containsKey('c')) { + context.handle(_cMeta, c.isAcceptableOrUnknown(data['c']!, _cMeta)); + } + return context; + } + + @override + Set get $primaryKey => const {}; + @override + WithConstraint map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return WithConstraint( + a: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}a']), + b: attachedDatabase.options.types + .read(DriftSqlType.int, data['${effectivePrefix}b'])!, + c: attachedDatabase.options.types + .read(DriftSqlType.double, data['${effectivePrefix}c']), + ); + } + + @override + $WithConstraintsTable createAlias(String alias) { + return $WithConstraintsTable(attachedDatabase, alias); + } } -@override -String toString() {return (StringBuffer('WithDefaultsCompanion(')..write('a: $a, ')..write('b: $b')..write(')')).toString();} + +class Config extends DataClass implements Insertable { + final String configKey; + final String? configValue; + final SyncType? syncState; + final SyncType? syncStateImplicit; + const Config( + {required this.configKey, + this.configValue, + this.syncState, + this.syncStateImplicit}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['config_key'] = Variable(configKey); + if (!nullToAbsent || configValue != null) { + map['config_value'] = Variable(configValue); + } + if (!nullToAbsent || syncState != null) { + final converter = $ConfigTable.$convertersyncState; + map['sync_state'] = Variable(converter.toSql(syncState)); + } + if (!nullToAbsent || syncStateImplicit != null) { + final converter = $ConfigTable.$convertersyncStateImplicit; + map['sync_state_implicit'] = + Variable(converter.toSql(syncStateImplicit)); + } + return map; + } + + ConfigCompanion toCompanion(bool nullToAbsent) { + return ConfigCompanion( + configKey: Value(configKey), + configValue: configValue == null && nullToAbsent + ? const Value.absent() + : Value(configValue), + syncState: syncState == null && nullToAbsent + ? const Value.absent() + : Value(syncState), + syncStateImplicit: syncStateImplicit == null && nullToAbsent + ? const Value.absent() + : Value(syncStateImplicit), + ); + } + + factory Config.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return Config( + configKey: serializer.fromJson(json['config_key']), + configValue: serializer.fromJson(json['config_value']), + syncState: serializer.fromJson(json['sync_state']), + syncStateImplicit: + serializer.fromJson(json['sync_state_implicit']), + ); + } + factory Config.fromJsonString(String encodedJson, + {ValueSerializer? serializer}) => + Config.fromJson(DataClass.parseJson(encodedJson) as Map, + serializer: serializer); + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'config_key': serializer.toJson(configKey), + 'config_value': serializer.toJson(configValue), + 'sync_state': serializer.toJson(syncState), + 'sync_state_implicit': serializer.toJson(syncStateImplicit), + }; + } + + Config copyWith( + {String? configKey, + Value configValue = const Value.absent(), + Value syncState = const Value.absent(), + Value syncStateImplicit = const Value.absent()}) => + Config( + configKey: configKey ?? this.configKey, + configValue: configValue.present ? configValue.value : this.configValue, + syncState: syncState.present ? syncState.value : this.syncState, + syncStateImplicit: syncStateImplicit.present + ? syncStateImplicit.value + : this.syncStateImplicit, + ); + @override + String toString() { + return (StringBuffer('Config(') + ..write('configKey: $configKey, ') + ..write('configValue: $configValue, ') + ..write('syncState: $syncState, ') + ..write('syncStateImplicit: $syncStateImplicit') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(configKey, configValue, syncState, syncStateImplicit); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is Config && + other.configKey == this.configKey && + other.configValue == this.configValue && + other.syncState == this.syncState && + other.syncStateImplicit == this.syncStateImplicit); } -class $WithDefaultsTable extends Table with TableInfo<$WithDefaultsTable, WithDefault> { -@override final GeneratedDatabase attachedDatabase; -final String? _alias; -$WithDefaultsTable(this.attachedDatabase, [this._alias]); -final VerificationMeta _aMeta = const VerificationMeta('a'); -late final GeneratedColumn a = GeneratedColumn('a', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); -final VerificationMeta _bMeta = const VerificationMeta('b'); -late final GeneratedColumn b = GeneratedColumn('b', aliasedName, true, type: DriftSqlType.int, requiredDuringInsert: false); -@override -List get $columns => [a, b]; -@override -String get aliasedName => _alias ?? 'with_defaults'; -@override - String get actualTableName => 'with_defaults'; -@override -VerificationContext validateIntegrity(Insertable instance, {bool isInserting = false}) { -final context = VerificationContext(); -final data = instance.toColumns(true); -if (data.containsKey('a')) { -context.handle(_aMeta, a.isAcceptableOrUnknown(data['a']!, _aMeta));}if (data.containsKey('b')) { -context.handle(_bMeta, b.isAcceptableOrUnknown(data['b']!, _bMeta));}return context; -} -@override -Set get $primaryKey => const {};@override WithDefault map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return WithDefault(a: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}a']), b: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}b']), ); -} -@override -$WithDefaultsTable createAlias(String alias) { -return $WithDefaultsTable(attachedDatabase, alias);}}class WithConstraint extends DataClass implements Insertable { -final String? a; -final int b; -final double? c; -const WithConstraint({this.a, required this.b, this.c});@override -Map toColumns(bool nullToAbsent) { -final map = {};if (!nullToAbsent || a != null){map['a'] = Variable(a);}map['b'] = Variable(b);if (!nullToAbsent || c != null){map['c'] = Variable(c);}return map; -} -WithConstraintsCompanion toCompanion(bool nullToAbsent) { -return WithConstraintsCompanion(a: a == null && nullToAbsent ? const Value.absent() : Value (a),b: Value (b),c: c == null && nullToAbsent ? const Value.absent() : Value (c),); -} -factory WithConstraint.fromJson(Map json, {ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return WithConstraint(a: serializer.fromJson(json['a']),b: serializer.fromJson(json['b']),c: serializer.fromJson(json['c']),);} -factory WithConstraint.fromJsonString(String encodedJson, {ValueSerializer? serializer}) => WithConstraint.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer);@override Map toJson({ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return { -'a': serializer.toJson(a),'b': serializer.toJson(b),'c': serializer.toJson(c),};}WithConstraint copyWith({Value a = const Value.absent(),int? b,Value c = const Value.absent()}) => WithConstraint(a: a.present ? a.value : this.a,b: b ?? this.b,c: c.present ? c.value : this.c,);@override -String toString() {return (StringBuffer('WithConstraint(')..write('a: $a, ')..write('b: $b, ')..write('c: $c')..write(')')).toString();} -@override - int get hashCode => Object.hash(a, b, c);@override -bool operator ==(Object other) => identical(this, other) || (other is WithConstraint && other.a == this.a && other.b == this.b && other.c == this.c); -}class WithConstraintsCompanion extends UpdateCompanion { -final Value a; -final Value b; -final Value c; -const WithConstraintsCompanion({this.a = const Value.absent(),this.b = const Value.absent(),this.c = const Value.absent(),}); -WithConstraintsCompanion.insert({this.a = const Value.absent(),required int b,this.c = const Value.absent(),}): b = Value(b); -static Insertable custom({Expression? a, -Expression? b, -Expression? c, -}) { -return RawValuesInsertable({if (a != null)'a': a,if (b != null)'b': b,if (c != null)'c': c,}); -}WithConstraintsCompanion copyWith({Value? a, Value? b, Value? c}) { -return WithConstraintsCompanion(a: a ?? this.a,b: b ?? this.b,c: c ?? this.c,); -} -@override -Map toColumns(bool nullToAbsent) { -final map = {};if (a.present) {map['a'] = Variable(a.value);}if (b.present) {map['b'] = Variable(b.value);}if (c.present) {map['c'] = Variable(c.value);}return map; -} -@override -String toString() {return (StringBuffer('WithConstraintsCompanion(')..write('a: $a, ')..write('b: $b, ')..write('c: $c')..write(')')).toString();} -} -class $WithConstraintsTable extends Table with TableInfo<$WithConstraintsTable, WithConstraint> { -@override final GeneratedDatabase attachedDatabase; -final String? _alias; -$WithConstraintsTable(this.attachedDatabase, [this._alias]); -final VerificationMeta _aMeta = const VerificationMeta('a'); -late final GeneratedColumn a = GeneratedColumn('a', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); -final VerificationMeta _bMeta = const VerificationMeta('b'); -late final GeneratedColumn b = GeneratedColumn('b', aliasedName, false, type: DriftSqlType.int, requiredDuringInsert: true); -final VerificationMeta _cMeta = const VerificationMeta('c'); -late final GeneratedColumn c = GeneratedColumn('c', aliasedName, true, type: DriftSqlType.double, requiredDuringInsert: false); -@override -List get $columns => [a, b, c]; -@override -String get aliasedName => _alias ?? 'with_constraints'; -@override - String get actualTableName => 'with_constraints'; -@override -VerificationContext validateIntegrity(Insertable instance, {bool isInserting = false}) { -final context = VerificationContext(); -final data = instance.toColumns(true); -if (data.containsKey('a')) { -context.handle(_aMeta, a.isAcceptableOrUnknown(data['a']!, _aMeta));}if (data.containsKey('b')) { -context.handle(_bMeta, b.isAcceptableOrUnknown(data['b']!, _bMeta));} else if (isInserting) { -context.missing(_bMeta); -} -if (data.containsKey('c')) { -context.handle(_cMeta, c.isAcceptableOrUnknown(data['c']!, _cMeta));}return context; -} -@override -Set get $primaryKey => const {};@override WithConstraint map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return WithConstraint(a: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}a']), b: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}b'])!, c: attachedDatabase.options.types.read(DriftSqlType.double, data['${effectivePrefix}c']), ); -} -@override -$WithConstraintsTable createAlias(String alias) { -return $WithConstraintsTable(attachedDatabase, alias);}}class Config extends DataClass implements Insertable { -final String configKey; -final String? configValue; -final int? syncState; -final int? syncStateImplicit; -const Config({required this.configKey, this.configValue, this.syncState, this.syncStateImplicit});@override -Map toColumns(bool nullToAbsent) { -final map = {};map['config_key'] = Variable(configKey);if (!nullToAbsent || configValue != null){map['config_value'] = Variable(configValue);}if (!nullToAbsent || syncState != null){map['sync_state'] = Variable(syncState);}if (!nullToAbsent || syncStateImplicit != null){map['sync_state_implicit'] = Variable(syncStateImplicit);}return map; -} -ConfigCompanion toCompanion(bool nullToAbsent) { -return ConfigCompanion(configKey: Value (configKey),configValue: configValue == null && nullToAbsent ? const Value.absent() : Value (configValue),syncState: syncState == null && nullToAbsent ? const Value.absent() : Value (syncState),syncStateImplicit: syncStateImplicit == null && nullToAbsent ? const Value.absent() : Value (syncStateImplicit),); -} -factory Config.fromJson(Map json, {ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return Config(configKey: serializer.fromJson(json['config_key']),configValue: serializer.fromJson(json['config_value']),syncState: serializer.fromJson(json['sync_state']),syncStateImplicit: serializer.fromJson(json['sync_state_implicit']),);} -factory Config.fromJsonString(String encodedJson, {ValueSerializer? serializer}) => Config.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer);@override Map toJson({ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return { -'config_key': serializer.toJson(configKey),'config_value': serializer.toJson(configValue),'sync_state': serializer.toJson(syncState),'sync_state_implicit': serializer.toJson(syncStateImplicit),};}Config copyWith({String? configKey,Value configValue = const Value.absent(),Value syncState = const Value.absent(),Value syncStateImplicit = const Value.absent()}) => Config(configKey: configKey ?? this.configKey,configValue: configValue.present ? configValue.value : this.configValue,syncState: syncState.present ? syncState.value : this.syncState,syncStateImplicit: syncStateImplicit.present ? syncStateImplicit.value : this.syncStateImplicit,);@override -String toString() {return (StringBuffer('Config(')..write('configKey: $configKey, ')..write('configValue: $configValue, ')..write('syncState: $syncState, ')..write('syncStateImplicit: $syncStateImplicit')..write(')')).toString();} -@override - int get hashCode => Object.hash(configKey, configValue, syncState, syncStateImplicit);@override -bool operator ==(Object other) => identical(this, other) || (other is Config && other.configKey == this.configKey && other.configValue == this.configValue && other.syncState == this.syncState && other.syncStateImplicit == this.syncStateImplicit); -}class ConfigCompanion extends UpdateCompanion { -final Value configKey; -final Value configValue; -final Value syncState; -final Value syncStateImplicit; -const ConfigCompanion({this.configKey = const Value.absent(),this.configValue = const Value.absent(),this.syncState = const Value.absent(),this.syncStateImplicit = const Value.absent(),}); -ConfigCompanion.insert({required String configKey,this.configValue = const Value.absent(),this.syncState = const Value.absent(),this.syncStateImplicit = const Value.absent(),}): configKey = Value(configKey); -static Insertable custom({Expression? configKey, -Expression? configValue, -Expression? syncState, -Expression? syncStateImplicit, -}) { -return RawValuesInsertable({if (configKey != null)'config_key': configKey,if (configValue != null)'config_value': configValue,if (syncState != null)'sync_state': syncState,if (syncStateImplicit != null)'sync_state_implicit': syncStateImplicit,}); -}ConfigCompanion copyWith({Value? configKey, Value? configValue, Value? syncState, Value? syncStateImplicit}) { -return ConfigCompanion(configKey: configKey ?? this.configKey,configValue: configValue ?? this.configValue,syncState: syncState ?? this.syncState,syncStateImplicit: syncStateImplicit ?? this.syncStateImplicit,); -} -@override -Map toColumns(bool nullToAbsent) { -final map = {};if (configKey.present) {map['config_key'] = Variable(configKey.value);}if (configValue.present) {map['config_value'] = Variable(configValue.value);}if (syncState.present) {map['sync_state'] = Variable(syncState.value);}if (syncStateImplicit.present) {map['sync_state_implicit'] = Variable(syncStateImplicit.value);}return map; -} -@override -String toString() {return (StringBuffer('ConfigCompanion(')..write('configKey: $configKey, ')..write('configValue: $configValue, ')..write('syncState: $syncState, ')..write('syncStateImplicit: $syncStateImplicit')..write(')')).toString();} + +class ConfigCompanion extends UpdateCompanion { + final Value configKey; + final Value configValue; + final Value syncState; + final Value syncStateImplicit; + const ConfigCompanion({ + this.configKey = const Value.absent(), + this.configValue = const Value.absent(), + this.syncState = const Value.absent(), + this.syncStateImplicit = const Value.absent(), + }); + ConfigCompanion.insert({ + required String configKey, + this.configValue = const Value.absent(), + this.syncState = const Value.absent(), + this.syncStateImplicit = const Value.absent(), + }) : configKey = Value(configKey); + static Insertable custom({ + Expression? configKey, + Expression? configValue, + Expression? syncState, + Expression? syncStateImplicit, + }) { + return RawValuesInsertable({ + if (configKey != null) 'config_key': configKey, + if (configValue != null) 'config_value': configValue, + if (syncState != null) 'sync_state': syncState, + if (syncStateImplicit != null) 'sync_state_implicit': syncStateImplicit, + }); + } + + ConfigCompanion copyWith( + {Value? configKey, + Value? configValue, + Value? syncState, + Value? syncStateImplicit}) { + return ConfigCompanion( + configKey: configKey ?? this.configKey, + configValue: configValue ?? this.configValue, + syncState: syncState ?? this.syncState, + syncStateImplicit: syncStateImplicit ?? this.syncStateImplicit, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (configKey.present) { + map['config_key'] = Variable(configKey.value); + } + if (configValue.present) { + map['config_value'] = Variable(configValue.value); + } + if (syncState.present) { + final converter = $ConfigTable.$convertersyncState; + map['sync_state'] = Variable(converter.toSql(syncState.value)); + } + if (syncStateImplicit.present) { + final converter = $ConfigTable.$convertersyncStateImplicit; + map['sync_state_implicit'] = + Variable(converter.toSql(syncStateImplicit.value)); + } + return map; + } + + @override + String toString() { + return (StringBuffer('ConfigCompanion(') + ..write('configKey: $configKey, ') + ..write('configValue: $configValue, ') + ..write('syncState: $syncState, ') + ..write('syncStateImplicit: $syncStateImplicit') + ..write(')')) + .toString(); + } } + class $ConfigTable extends Table with TableInfo<$ConfigTable, Config> { -@override final GeneratedDatabase attachedDatabase; -final String? _alias; -$ConfigTable(this.attachedDatabase, [this._alias]); -final VerificationMeta _configKeyMeta = const VerificationMeta('configKey'); -late final GeneratedColumn configKey = GeneratedColumn('config_key', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); -final VerificationMeta _configValueMeta = const VerificationMeta('configValue'); -late final GeneratedColumn configValue = GeneratedColumn('config_value', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); -final VerificationMeta _syncStateMeta = const VerificationMeta('syncState'); -late final GeneratedColumn syncState = GeneratedColumn('sync_state', aliasedName, true, type: DriftSqlType.int, requiredDuringInsert: false); -final VerificationMeta _syncStateImplicitMeta = const VerificationMeta('syncStateImplicit'); -late final GeneratedColumn syncStateImplicit = GeneratedColumn('sync_state_implicit', aliasedName, true, type: DriftSqlType.int, requiredDuringInsert: false); -@override -List get $columns => [configKey, configValue, syncState, syncStateImplicit]; -@override -String get aliasedName => _alias ?? 'config'; -@override - String get actualTableName => 'config'; -@override -VerificationContext validateIntegrity(Insertable instance, {bool isInserting = false}) { -final context = VerificationContext(); -final data = instance.toColumns(true); -if (data.containsKey('config_key')) { -context.handle(_configKeyMeta, configKey.isAcceptableOrUnknown(data['config_key']!, _configKeyMeta));} else if (isInserting) { -context.missing(_configKeyMeta); + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $ConfigTable(this.attachedDatabase, [this._alias]); + final VerificationMeta _configKeyMeta = const VerificationMeta('configKey'); + late final GeneratedColumn configKey = GeneratedColumn( + 'config_key', aliasedName, false, + type: DriftSqlType.string, requiredDuringInsert: true); + final VerificationMeta _configValueMeta = + const VerificationMeta('configValue'); + late final GeneratedColumn configValue = GeneratedColumn( + 'config_value', aliasedName, true, + type: DriftSqlType.string, requiredDuringInsert: false); + final VerificationMeta _syncStateMeta = const VerificationMeta('syncState'); + late final GeneratedColumnWithTypeConverter syncState = + GeneratedColumn('sync_state', aliasedName, true, + type: DriftSqlType.int, requiredDuringInsert: false) + .withConverter($ConfigTable.$convertersyncState); + final VerificationMeta _syncStateImplicitMeta = + const VerificationMeta('syncStateImplicit'); + late final GeneratedColumnWithTypeConverter + syncStateImplicit = GeneratedColumn( + 'sync_state_implicit', aliasedName, true, + type: DriftSqlType.int, requiredDuringInsert: false) + .withConverter($ConfigTable.$convertersyncStateImplicit); + @override + List get $columns => + [configKey, configValue, syncState, syncStateImplicit]; + @override + String get aliasedName => _alias ?? 'config'; + @override + String get actualTableName => 'config'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('config_key')) { + context.handle(_configKeyMeta, + configKey.isAcceptableOrUnknown(data['config_key']!, _configKeyMeta)); + } else if (isInserting) { + context.missing(_configKeyMeta); + } + if (data.containsKey('config_value')) { + context.handle( + _configValueMeta, + configValue.isAcceptableOrUnknown( + data['config_value']!, _configValueMeta)); + } + context.handle(_syncStateMeta, const VerificationResult.success()); + context.handle(_syncStateImplicitMeta, const VerificationResult.success()); + return context; + } + + @override + Set get $primaryKey => const {}; + @override + Config map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return Config( + configKey: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}config_key'])!, + configValue: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}config_value']), + syncState: $ConfigTable.$convertersyncState.fromSql(attachedDatabase + .options.types + .read(DriftSqlType.int, data['${effectivePrefix}sync_state'])), + syncStateImplicit: $ConfigTable.$convertersyncStateImplicit.fromSql( + attachedDatabase.options.types.read( + DriftSqlType.int, data['${effectivePrefix}sync_state_implicit'])), + ); + } + + @override + $ConfigTable createAlias(String alias) { + return $ConfigTable(attachedDatabase, alias); + } + + static TypeConverter $convertersyncState = + const SyncTypeConverter(); + static TypeConverter $convertersyncStaten = + NullAwareTypeConverter.wrap($convertersyncState); + static TypeConverter $convertersyncStateImplicit = + const EnumIndexConverter(SyncType.values); + static TypeConverter $convertersyncStateImplicitn = + NullAwareTypeConverter.wrap($convertersyncStateImplicit); + @override + bool get isStrict => true; } -if (data.containsKey('config_value')) { -context.handle(_configValueMeta, configValue.isAcceptableOrUnknown(data['config_value']!, _configValueMeta));}if (data.containsKey('sync_state')) { -context.handle(_syncStateMeta, syncState.isAcceptableOrUnknown(data['sync_state']!, _syncStateMeta));}if (data.containsKey('sync_state_implicit')) { -context.handle(_syncStateImplicitMeta, syncStateImplicit.isAcceptableOrUnknown(data['sync_state_implicit']!, _syncStateImplicitMeta));}return context; + +class MytableData extends DataClass implements Insertable { + final int someid; + final String? sometext; + final bool? isInserting; + final DateTime? somedate; + const MytableData( + {required this.someid, this.sometext, this.isInserting, this.somedate}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['someid'] = Variable(someid); + if (!nullToAbsent || sometext != null) { + map['sometext'] = Variable(sometext); + } + if (!nullToAbsent || isInserting != null) { + map['is_inserting'] = Variable(isInserting); + } + if (!nullToAbsent || somedate != null) { + map['somedate'] = Variable(somedate); + } + return map; + } + + MytableCompanion toCompanion(bool nullToAbsent) { + return MytableCompanion( + someid: Value(someid), + sometext: sometext == null && nullToAbsent + ? const Value.absent() + : Value(sometext), + isInserting: isInserting == null && nullToAbsent + ? const Value.absent() + : Value(isInserting), + somedate: somedate == null && nullToAbsent + ? const Value.absent() + : Value(somedate), + ); + } + + factory MytableData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return MytableData( + someid: serializer.fromJson(json['someid']), + sometext: serializer.fromJson(json['sometext']), + isInserting: serializer.fromJson(json['is_inserting']), + somedate: serializer.fromJson(json['somedate']), + ); + } + factory MytableData.fromJsonString(String encodedJson, + {ValueSerializer? serializer}) => + MytableData.fromJson( + DataClass.parseJson(encodedJson) as Map, + serializer: serializer); + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'someid': serializer.toJson(someid), + 'sometext': serializer.toJson(sometext), + 'is_inserting': serializer.toJson(isInserting), + 'somedate': serializer.toJson(somedate), + }; + } + + MytableData copyWith( + {int? someid, + Value sometext = const Value.absent(), + Value isInserting = const Value.absent(), + Value somedate = const Value.absent()}) => + MytableData( + someid: someid ?? this.someid, + sometext: sometext.present ? sometext.value : this.sometext, + isInserting: isInserting.present ? isInserting.value : this.isInserting, + somedate: somedate.present ? somedate.value : this.somedate, + ); + @override + String toString() { + return (StringBuffer('MytableData(') + ..write('someid: $someid, ') + ..write('sometext: $sometext, ') + ..write('isInserting: $isInserting, ') + ..write('somedate: $somedate') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(someid, sometext, isInserting, somedate); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is MytableData && + other.someid == this.someid && + other.sometext == this.sometext && + other.isInserting == this.isInserting && + other.somedate == this.somedate); } -@override -Set get $primaryKey => const {};@override Config map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return Config(configKey: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}config_key'])!, configValue: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}config_value']), syncState: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}sync_state']), syncStateImplicit: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}sync_state_implicit']), ); -} -@override -$ConfigTable createAlias(String alias) { -return $ConfigTable(attachedDatabase, alias);}@override -bool get isStrict => true; -}class MytableData extends DataClass implements Insertable { -final int someid; -final String? sometext; -final bool? isInserting; -final DateTime? somedate; -const MytableData({required this.someid, this.sometext, this.isInserting, this.somedate});@override -Map toColumns(bool nullToAbsent) { -final map = {};map['someid'] = Variable(someid);if (!nullToAbsent || sometext != null){map['sometext'] = Variable(sometext);}if (!nullToAbsent || isInserting != null){map['is_inserting'] = Variable(isInserting);}if (!nullToAbsent || somedate != null){map['somedate'] = Variable(somedate);}return map; -} -MytableCompanion toCompanion(bool nullToAbsent) { -return MytableCompanion(someid: Value (someid),sometext: sometext == null && nullToAbsent ? const Value.absent() : Value (sometext),isInserting: isInserting == null && nullToAbsent ? const Value.absent() : Value (isInserting),somedate: somedate == null && nullToAbsent ? const Value.absent() : Value (somedate),); -} -factory MytableData.fromJson(Map json, {ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return MytableData(someid: serializer.fromJson(json['someid']),sometext: serializer.fromJson(json['sometext']),isInserting: serializer.fromJson(json['is_inserting']),somedate: serializer.fromJson(json['somedate']),);} -factory MytableData.fromJsonString(String encodedJson, {ValueSerializer? serializer}) => MytableData.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer);@override Map toJson({ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return { -'someid': serializer.toJson(someid),'sometext': serializer.toJson(sometext),'is_inserting': serializer.toJson(isInserting),'somedate': serializer.toJson(somedate),};}MytableData copyWith({int? someid,Value sometext = const Value.absent(),Value isInserting = const Value.absent(),Value somedate = const Value.absent()}) => MytableData(someid: someid ?? this.someid,sometext: sometext.present ? sometext.value : this.sometext,isInserting: isInserting.present ? isInserting.value : this.isInserting,somedate: somedate.present ? somedate.value : this.somedate,);@override -String toString() {return (StringBuffer('MytableData(')..write('someid: $someid, ')..write('sometext: $sometext, ')..write('isInserting: $isInserting, ')..write('somedate: $somedate')..write(')')).toString();} -@override - int get hashCode => Object.hash(someid, sometext, isInserting, somedate);@override -bool operator ==(Object other) => identical(this, other) || (other is MytableData && other.someid == this.someid && other.sometext == this.sometext && other.isInserting == this.isInserting && other.somedate == this.somedate); -}class MytableCompanion extends UpdateCompanion { -final Value someid; -final Value sometext; -final Value isInserting; -final Value somedate; -const MytableCompanion({this.someid = const Value.absent(),this.sometext = const Value.absent(),this.isInserting = const Value.absent(),this.somedate = const Value.absent(),}); -MytableCompanion.insert({required int someid,this.sometext = const Value.absent(),this.isInserting = const Value.absent(),this.somedate = const Value.absent(),}): someid = Value(someid); -static Insertable custom({Expression? someid, -Expression? sometext, -Expression? isInserting, -Expression? somedate, -}) { -return RawValuesInsertable({if (someid != null)'someid': someid,if (sometext != null)'sometext': sometext,if (isInserting != null)'is_inserting': isInserting,if (somedate != null)'somedate': somedate,}); -}MytableCompanion copyWith({Value? someid, Value? sometext, Value? isInserting, Value? somedate}) { -return MytableCompanion(someid: someid ?? this.someid,sometext: sometext ?? this.sometext,isInserting: isInserting ?? this.isInserting,somedate: somedate ?? this.somedate,); -} -@override -Map toColumns(bool nullToAbsent) { -final map = {};if (someid.present) {map['someid'] = Variable(someid.value);}if (sometext.present) {map['sometext'] = Variable(sometext.value);}if (isInserting.present) {map['is_inserting'] = Variable(isInserting.value);}if (somedate.present) {map['somedate'] = Variable(somedate.value);}return map; -} -@override -String toString() {return (StringBuffer('MytableCompanion(')..write('someid: $someid, ')..write('sometext: $sometext, ')..write('isInserting: $isInserting, ')..write('somedate: $somedate')..write(')')).toString();} + +class MytableCompanion extends UpdateCompanion { + final Value someid; + final Value sometext; + final Value isInserting; + final Value somedate; + const MytableCompanion({ + this.someid = const Value.absent(), + this.sometext = const Value.absent(), + this.isInserting = const Value.absent(), + this.somedate = const Value.absent(), + }); + MytableCompanion.insert({ + required int someid, + this.sometext = const Value.absent(), + this.isInserting = const Value.absent(), + this.somedate = const Value.absent(), + }) : someid = Value(someid); + static Insertable custom({ + Expression? someid, + Expression? sometext, + Expression? isInserting, + Expression? somedate, + }) { + return RawValuesInsertable({ + if (someid != null) 'someid': someid, + if (sometext != null) 'sometext': sometext, + if (isInserting != null) 'is_inserting': isInserting, + if (somedate != null) 'somedate': somedate, + }); + } + + MytableCompanion copyWith( + {Value? someid, + Value? sometext, + Value? isInserting, + Value? somedate}) { + return MytableCompanion( + someid: someid ?? this.someid, + sometext: sometext ?? this.sometext, + isInserting: isInserting ?? this.isInserting, + somedate: somedate ?? this.somedate, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (someid.present) { + map['someid'] = Variable(someid.value); + } + if (sometext.present) { + map['sometext'] = Variable(sometext.value); + } + if (isInserting.present) { + map['is_inserting'] = Variable(isInserting.value); + } + if (somedate.present) { + map['somedate'] = Variable(somedate.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('MytableCompanion(') + ..write('someid: $someid, ') + ..write('sometext: $sometext, ') + ..write('isInserting: $isInserting, ') + ..write('somedate: $somedate') + ..write(')')) + .toString(); + } } + class $MytableTable extends Table with TableInfo<$MytableTable, MytableData> { -@override final GeneratedDatabase attachedDatabase; -final String? _alias; -$MytableTable(this.attachedDatabase, [this._alias]); -final VerificationMeta _someidMeta = const VerificationMeta('someid'); -late final GeneratedColumn someid = GeneratedColumn('someid', aliasedName, false, type: DriftSqlType.int, requiredDuringInsert: true); -final VerificationMeta _sometextMeta = const VerificationMeta('sometext'); -late final GeneratedColumn sometext = GeneratedColumn('sometext', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); -final VerificationMeta _isInsertingMeta = const VerificationMeta('isInserting'); -late final GeneratedColumn isInserting = GeneratedColumn('is_inserting', aliasedName, true, type: DriftSqlType.bool, requiredDuringInsert: false, defaultConstraints: 'CHECK (is_inserting IN (0, 1))'); -final VerificationMeta _somedateMeta = const VerificationMeta('somedate'); -late final GeneratedColumn somedate = GeneratedColumn('somedate', aliasedName, true, type: DriftSqlType.dateTime, requiredDuringInsert: false); -@override -List get $columns => [someid, sometext, isInserting, somedate]; -@override -String get aliasedName => _alias ?? 'mytable'; -@override - String get actualTableName => 'mytable'; -@override -VerificationContext validateIntegrity(Insertable instance, {bool isInserting = false}) { -final context = VerificationContext(); -final data = instance.toColumns(true); -if (data.containsKey('someid')) { -context.handle(_someidMeta, someid.isAcceptableOrUnknown(data['someid']!, _someidMeta));} else if (isInserting) { -context.missing(_someidMeta); + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $MytableTable(this.attachedDatabase, [this._alias]); + final VerificationMeta _someidMeta = const VerificationMeta('someid'); + late final GeneratedColumn someid = GeneratedColumn( + 'someid', aliasedName, false, + type: DriftSqlType.int, requiredDuringInsert: true); + final VerificationMeta _sometextMeta = const VerificationMeta('sometext'); + late final GeneratedColumn sometext = GeneratedColumn( + 'sometext', aliasedName, true, + type: DriftSqlType.string, requiredDuringInsert: false); + final VerificationMeta _isInsertingMeta = + const VerificationMeta('isInserting'); + late final GeneratedColumn isInserting = GeneratedColumn( + 'is_inserting', aliasedName, true, + type: DriftSqlType.bool, + requiredDuringInsert: false, + defaultConstraints: 'CHECK (is_inserting IN (0, 1))'); + final VerificationMeta _somedateMeta = const VerificationMeta('somedate'); + late final GeneratedColumn somedate = GeneratedColumn( + 'somedate', aliasedName, true, + type: DriftSqlType.dateTime, requiredDuringInsert: false); + @override + List get $columns => + [someid, sometext, isInserting, somedate]; + @override + String get aliasedName => _alias ?? 'mytable'; + @override + String get actualTableName => 'mytable'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('someid')) { + context.handle(_someidMeta, + someid.isAcceptableOrUnknown(data['someid']!, _someidMeta)); + } else if (isInserting) { + context.missing(_someidMeta); + } + if (data.containsKey('sometext')) { + context.handle(_sometextMeta, + sometext.isAcceptableOrUnknown(data['sometext']!, _sometextMeta)); + } + if (data.containsKey('is_inserting')) { + context.handle( + _isInsertingMeta, + this + .isInserting + .isAcceptableOrUnknown(data['is_inserting']!, _isInsertingMeta)); + } + if (data.containsKey('somedate')) { + context.handle(_somedateMeta, + somedate.isAcceptableOrUnknown(data['somedate']!, _somedateMeta)); + } + return context; + } + + @override + Set get $primaryKey => const {}; + @override + MytableData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return MytableData( + someid: attachedDatabase.options.types + .read(DriftSqlType.int, data['${effectivePrefix}someid'])!, + sometext: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}sometext']), + isInserting: attachedDatabase.options.types + .read(DriftSqlType.bool, data['${effectivePrefix}is_inserting']), + somedate: attachedDatabase.options.types + .read(DriftSqlType.dateTime, data['${effectivePrefix}somedate']), + ); + } + + @override + $MytableTable createAlias(String alias) { + return $MytableTable(attachedDatabase, alias); + } } -if (data.containsKey('sometext')) { -context.handle(_sometextMeta, sometext.isAcceptableOrUnknown(data['sometext']!, _sometextMeta));}if (data.containsKey('is_inserting')) { -context.handle(_isInsertingMeta, this.isInserting.isAcceptableOrUnknown(data['is_inserting']!, _isInsertingMeta));}if (data.containsKey('somedate')) { -context.handle(_somedateMeta, somedate.isAcceptableOrUnknown(data['somedate']!, _somedateMeta));}return context; + +class EMail extends DataClass implements Insertable { + final String sender; + final String title; + final String body; + const EMail({required this.sender, required this.title, required this.body}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['sender'] = Variable(sender); + map['title'] = Variable(title); + map['body'] = Variable(body); + return map; + } + + EmailCompanion toCompanion(bool nullToAbsent) { + return EmailCompanion( + sender: Value(sender), + title: Value(title), + body: Value(body), + ); + } + + factory EMail.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return EMail( + sender: serializer.fromJson(json['sender']), + title: serializer.fromJson(json['title']), + body: serializer.fromJson(json['body']), + ); + } + factory EMail.fromJsonString(String encodedJson, + {ValueSerializer? serializer}) => + EMail.fromJson(DataClass.parseJson(encodedJson) as Map, + serializer: serializer); + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'sender': serializer.toJson(sender), + 'title': serializer.toJson(title), + 'body': serializer.toJson(body), + }; + } + + EMail copyWith({String? sender, String? title, String? body}) => EMail( + sender: sender ?? this.sender, + title: title ?? this.title, + body: body ?? this.body, + ); + @override + String toString() { + return (StringBuffer('EMail(') + ..write('sender: $sender, ') + ..write('title: $title, ') + ..write('body: $body') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(sender, title, body); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is EMail && + other.sender == this.sender && + other.title == this.title && + other.body == this.body); } -@override -Set get $primaryKey => const {};@override MytableData map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return MytableData(someid: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}someid'])!, sometext: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}sometext']), isInserting: attachedDatabase.options.types.read(DriftSqlType.bool, data['${effectivePrefix}is_inserting']), somedate: attachedDatabase.options.types.read(DriftSqlType.dateTime, data['${effectivePrefix}somedate']), ); + +class EmailCompanion extends UpdateCompanion { + final Value sender; + final Value title; + final Value body; + const EmailCompanion({ + this.sender = const Value.absent(), + this.title = const Value.absent(), + this.body = const Value.absent(), + }); + EmailCompanion.insert({ + required String sender, + required String title, + required String body, + }) : sender = Value(sender), + title = Value(title), + body = Value(body); + static Insertable custom({ + Expression? sender, + Expression? title, + Expression? body, + }) { + return RawValuesInsertable({ + if (sender != null) 'sender': sender, + if (title != null) 'title': title, + if (body != null) 'body': body, + }); + } + + EmailCompanion copyWith( + {Value? sender, Value? title, Value? body}) { + return EmailCompanion( + sender: sender ?? this.sender, + title: title ?? this.title, + body: body ?? this.body, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (sender.present) { + map['sender'] = Variable(sender.value); + } + if (title.present) { + map['title'] = Variable(title.value); + } + if (body.present) { + map['body'] = Variable(body.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('EmailCompanion(') + ..write('sender: $sender, ') + ..write('title: $title, ') + ..write('body: $body') + ..write(')')) + .toString(); + } } -@override -$MytableTable createAlias(String alias) { -return $MytableTable(attachedDatabase, alias);}}class EMail extends DataClass implements Insertable { -final String sender; -final String title; -final String body; -const EMail({required this.sender, required this.title, required this.body});@override -Map toColumns(bool nullToAbsent) { -final map = {};map['sender'] = Variable(sender);map['title'] = Variable(title);map['body'] = Variable(body);return map; + +class $EmailTable extends Table + with TableInfo<$EmailTable, EMail>, VirtualTableInfo<$EmailTable, EMail> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $EmailTable(this.attachedDatabase, [this._alias]); + final VerificationMeta _senderMeta = const VerificationMeta('sender'); + late final GeneratedColumn sender = GeneratedColumn( + 'sender', aliasedName, false, + type: DriftSqlType.string, requiredDuringInsert: true); + final VerificationMeta _titleMeta = const VerificationMeta('title'); + late final GeneratedColumn title = GeneratedColumn( + 'title', aliasedName, false, + type: DriftSqlType.string, requiredDuringInsert: true); + final VerificationMeta _bodyMeta = const VerificationMeta('body'); + late final GeneratedColumn body = GeneratedColumn( + 'body', aliasedName, false, + type: DriftSqlType.string, requiredDuringInsert: true); + @override + List get $columns => [sender, title, body]; + @override + String get aliasedName => _alias ?? 'email'; + @override + String get actualTableName => 'email'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('sender')) { + context.handle(_senderMeta, + sender.isAcceptableOrUnknown(data['sender']!, _senderMeta)); + } else if (isInserting) { + context.missing(_senderMeta); + } + if (data.containsKey('title')) { + context.handle( + _titleMeta, title.isAcceptableOrUnknown(data['title']!, _titleMeta)); + } else if (isInserting) { + context.missing(_titleMeta); + } + if (data.containsKey('body')) { + context.handle( + _bodyMeta, body.isAcceptableOrUnknown(data['body']!, _bodyMeta)); + } else if (isInserting) { + context.missing(_bodyMeta); + } + return context; + } + + @override + Set get $primaryKey => const {}; + @override + EMail map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return EMail( + sender: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}sender'])!, + title: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}title'])!, + body: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}body'])!, + ); + } + + @override + $EmailTable createAlias(String alias) { + return $EmailTable(attachedDatabase, alias); + } + + @override + String get moduleAndArgs => 'fts5(sender, title, body)'; } -EmailCompanion toCompanion(bool nullToAbsent) { -return EmailCompanion(sender: Value (sender),title: Value (title),body: Value (body),); + +class WeirdData extends DataClass implements Insertable { + final int sqlClass; + final String textColumn; + const WeirdData({required this.sqlClass, required this.textColumn}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['class'] = Variable(sqlClass); + map['text'] = Variable(textColumn); + return map; + } + + WeirdTableCompanion toCompanion(bool nullToAbsent) { + return WeirdTableCompanion( + sqlClass: Value(sqlClass), + textColumn: Value(textColumn), + ); + } + + factory WeirdData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return WeirdData( + sqlClass: serializer.fromJson(json['class']), + textColumn: serializer.fromJson(json['text']), + ); + } + factory WeirdData.fromJsonString(String encodedJson, + {ValueSerializer? serializer}) => + WeirdData.fromJson( + DataClass.parseJson(encodedJson) as Map, + serializer: serializer); + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'class': serializer.toJson(sqlClass), + 'text': serializer.toJson(textColumn), + }; + } + + WeirdData copyWith({int? sqlClass, String? textColumn}) => WeirdData( + sqlClass: sqlClass ?? this.sqlClass, + textColumn: textColumn ?? this.textColumn, + ); + @override + String toString() { + return (StringBuffer('WeirdData(') + ..write('sqlClass: $sqlClass, ') + ..write('textColumn: $textColumn') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(sqlClass, textColumn); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is WeirdData && + other.sqlClass == this.sqlClass && + other.textColumn == this.textColumn); } -factory EMail.fromJson(Map json, {ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return EMail(sender: serializer.fromJson(json['sender']),title: serializer.fromJson(json['title']),body: serializer.fromJson(json['body']),);} -factory EMail.fromJsonString(String encodedJson, {ValueSerializer? serializer}) => EMail.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer);@override Map toJson({ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return { -'sender': serializer.toJson(sender),'title': serializer.toJson(title),'body': serializer.toJson(body),};}EMail copyWith({String? sender,String? title,String? body}) => EMail(sender: sender ?? this.sender,title: title ?? this.title,body: body ?? this.body,);@override -String toString() {return (StringBuffer('EMail(')..write('sender: $sender, ')..write('title: $title, ')..write('body: $body')..write(')')).toString();} -@override - int get hashCode => Object.hash(sender, title, body);@override -bool operator ==(Object other) => identical(this, other) || (other is EMail && other.sender == this.sender && other.title == this.title && other.body == this.body); -}class EmailCompanion extends UpdateCompanion { -final Value sender; -final Value title; -final Value body; -const EmailCompanion({this.sender = const Value.absent(),this.title = const Value.absent(),this.body = const Value.absent(),}); -EmailCompanion.insert({required String sender,required String title,required String body,}): sender = Value(sender), title = Value(title), body = Value(body); -static Insertable custom({Expression? sender, -Expression? title, -Expression? body, -}) { -return RawValuesInsertable({if (sender != null)'sender': sender,if (title != null)'title': title,if (body != null)'body': body,}); -}EmailCompanion copyWith({Value? sender, Value? title, Value? body}) { -return EmailCompanion(sender: sender ?? this.sender,title: title ?? this.title,body: body ?? this.body,); + +class WeirdTableCompanion extends UpdateCompanion { + final Value sqlClass; + final Value textColumn; + const WeirdTableCompanion({ + this.sqlClass = const Value.absent(), + this.textColumn = const Value.absent(), + }); + WeirdTableCompanion.insert({ + required int sqlClass, + required String textColumn, + }) : sqlClass = Value(sqlClass), + textColumn = Value(textColumn); + static Insertable custom({ + Expression? sqlClass, + Expression? textColumn, + }) { + return RawValuesInsertable({ + if (sqlClass != null) 'class': sqlClass, + if (textColumn != null) 'text': textColumn, + }); + } + + WeirdTableCompanion copyWith( + {Value? sqlClass, Value? textColumn}) { + return WeirdTableCompanion( + sqlClass: sqlClass ?? this.sqlClass, + textColumn: textColumn ?? this.textColumn, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (sqlClass.present) { + map['class'] = Variable(sqlClass.value); + } + if (textColumn.present) { + map['text'] = Variable(textColumn.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('WeirdTableCompanion(') + ..write('sqlClass: $sqlClass, ') + ..write('textColumn: $textColumn') + ..write(')')) + .toString(); + } } -@override -Map toColumns(bool nullToAbsent) { -final map = {};if (sender.present) {map['sender'] = Variable(sender.value);}if (title.present) {map['title'] = Variable(title.value);}if (body.present) {map['body'] = Variable(body.value);}return map; + +class $WeirdTableTable extends Table + with TableInfo<$WeirdTableTable, WeirdData> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $WeirdTableTable(this.attachedDatabase, [this._alias]); + final VerificationMeta _sqlClassMeta = const VerificationMeta('sqlClass'); + late final GeneratedColumn sqlClass = GeneratedColumn( + 'class', aliasedName, false, + type: DriftSqlType.int, requiredDuringInsert: true); + final VerificationMeta _textColumnMeta = const VerificationMeta('textColumn'); + late final GeneratedColumn textColumn = GeneratedColumn( + 'text', aliasedName, false, + type: DriftSqlType.string, requiredDuringInsert: true); + @override + List get $columns => [sqlClass, textColumn]; + @override + String get aliasedName => _alias ?? 'Expression'; + @override + String get actualTableName => 'Expression'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('class')) { + context.handle(_sqlClassMeta, + sqlClass.isAcceptableOrUnknown(data['class']!, _sqlClassMeta)); + } else if (isInserting) { + context.missing(_sqlClassMeta); + } + if (data.containsKey('text')) { + context.handle(_textColumnMeta, + textColumn.isAcceptableOrUnknown(data['text']!, _textColumnMeta)); + } else if (isInserting) { + context.missing(_textColumnMeta); + } + return context; + } + + @override + Set get $primaryKey => const {}; + @override + WeirdData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return WeirdData( + sqlClass: attachedDatabase.options.types + .read(DriftSqlType.int, data['${effectivePrefix}class'])!, + textColumn: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}text'])!, + ); + } + + @override + $WeirdTableTable createAlias(String alias) { + return $WeirdTableTable(attachedDatabase, alias); + } } -@override -String toString() {return (StringBuffer('EmailCompanion(')..write('sender: $sender, ')..write('title: $title, ')..write('body: $body')..write(')')).toString();} + +class MyViewData extends DataClass { + final String configKey; + final String configValue; + final SyncType syncState; + final SyncType syncStateImplicit; + const MyViewData( + {required this.configKey, + required this.configValue, + required this.syncState, + required this.syncStateImplicit}); + factory MyViewData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return MyViewData( + configKey: serializer.fromJson(json['config_key']), + configValue: serializer.fromJson(json['config_value']), + syncState: serializer.fromJson(json['sync_state']), + syncStateImplicit: + serializer.fromJson(json['sync_state_implicit']), + ); + } + factory MyViewData.fromJsonString(String encodedJson, + {ValueSerializer? serializer}) => + MyViewData.fromJson( + DataClass.parseJson(encodedJson) as Map, + serializer: serializer); + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'config_key': serializer.toJson(configKey), + 'config_value': serializer.toJson(configValue), + 'sync_state': serializer.toJson(syncState), + 'sync_state_implicit': serializer.toJson(syncStateImplicit), + }; + } + + MyViewData copyWith( + {String? configKey, + String? configValue, + SyncType? syncState, + SyncType? syncStateImplicit}) => + MyViewData( + configKey: configKey ?? this.configKey, + configValue: configValue ?? this.configValue, + syncState: syncState ?? this.syncState, + syncStateImplicit: syncStateImplicit ?? this.syncStateImplicit, + ); + @override + String toString() { + return (StringBuffer('MyViewData(') + ..write('configKey: $configKey, ') + ..write('configValue: $configValue, ') + ..write('syncState: $syncState, ') + ..write('syncStateImplicit: $syncStateImplicit') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(configKey, configValue, syncState, syncStateImplicit); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is MyViewData && + other.configKey == this.configKey && + other.configValue == this.configValue && + other.syncState == this.syncState && + other.syncStateImplicit == this.syncStateImplicit); } -class $EmailTable extends Table with TableInfo<$EmailTable, EMail> , VirtualTableInfo<$EmailTable, EMail> { -@override final GeneratedDatabase attachedDatabase; -final String? _alias; -$EmailTable(this.attachedDatabase, [this._alias]); -final VerificationMeta _senderMeta = const VerificationMeta('sender'); -late final GeneratedColumn sender = GeneratedColumn('sender', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); -final VerificationMeta _titleMeta = const VerificationMeta('title'); -late final GeneratedColumn title = GeneratedColumn('title', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); -final VerificationMeta _bodyMeta = const VerificationMeta('body'); -late final GeneratedColumn body = GeneratedColumn('body', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); -@override -List get $columns => [sender, title, body]; -@override -String get aliasedName => _alias ?? 'email'; -@override - String get actualTableName => 'email'; -@override -VerificationContext validateIntegrity(Insertable instance, {bool isInserting = false}) { -final context = VerificationContext(); -final data = instance.toColumns(true); -if (data.containsKey('sender')) { -context.handle(_senderMeta, sender.isAcceptableOrUnknown(data['sender']!, _senderMeta));} else if (isInserting) { -context.missing(_senderMeta); + +class MyView extends ViewInfo implements HasResultSet { + final String? _alias; + @override + final _$CustomTablesDb attachedDatabase; + MyView(this.attachedDatabase, [this._alias]); + @override + List get $columns => + [configKey, configValue, syncState, syncStateImplicit]; + @override + String get aliasedName => _alias ?? entityName; + @override + String get entityName => 'my_view'; + @override + String get createViewStmt => + 'CREATE VIEW my_view AS SELECT * FROM config WHERE sync_state = 2'; + @override + MyView get asDslTable => this; + @override + MyViewData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return MyViewData( + configKey: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}config_key'])!, + configValue: attachedDatabase.options.types + .read(DriftSqlType.string, data['${effectivePrefix}config_value'])!, + syncState: MyView.$convertersyncStaten.fromSql(attachedDatabase + .options.types + .read(DriftSqlType.int, data['${effectivePrefix}sync_state'])!), + syncStateImplicit: MyView.$convertersyncStateImplicitn.fromSql( + attachedDatabase.options.types.read(DriftSqlType.int, + data['${effectivePrefix}sync_state_implicit'])!), + ); + } + + late final GeneratedColumn configKey = GeneratedColumn( + 'config_key', aliasedName, false, + type: DriftSqlType.string); + late final GeneratedColumn configValue = GeneratedColumn( + 'config_value', aliasedName, false, + type: DriftSqlType.string); + late final GeneratedColumnWithTypeConverter syncState = + GeneratedColumn('sync_state', aliasedName, false, + type: DriftSqlType.int) + .withConverter(MyView.$convertersyncStaten); + late final GeneratedColumnWithTypeConverter syncStateImplicit = + GeneratedColumn('sync_state_implicit', aliasedName, false, + type: DriftSqlType.int) + .withConverter(MyView.$convertersyncStateImplicitn); + @override + MyView createAlias(String alias) { + return MyView(attachedDatabase, alias); + } + + @override + Query? get query => null; + @override + Set get readTables => const {'config'}; } -if (data.containsKey('title')) { -context.handle(_titleMeta, title.isAcceptableOrUnknown(data['title']!, _titleMeta));} else if (isInserting) { -context.missing(_titleMeta); + +abstract class _$CustomTablesDb extends GeneratedDatabase { + _$CustomTablesDb(QueryExecutor e) : super(e); + _$CustomTablesDb.connect(DatabaseConnection c) : super.connect(c); + late final $NoIdsTable noIds = $NoIdsTable(this); + late final $WithDefaultsTable withDefaults = $WithDefaultsTable(this); + late final $WithConstraintsTable withConstraints = + $WithConstraintsTable(this); + late final $ConfigTable config = $ConfigTable(this); + late final Index valueIdx = Index('value_idx', + 'CREATE INDEX IF NOT EXISTS value_idx ON config (config_value)'); + late final $MytableTable mytable = $MytableTable(this); + late final $EmailTable email = $EmailTable(this); + late final $WeirdTableTable weirdTable = $WeirdTableTable(this); + late final Trigger myTrigger = Trigger( + 'CREATE TRIGGER my_trigger AFTER INSERT ON config BEGIN INSERT INTO with_defaults VALUES (new.config_key, LENGTH(new.config_value));END', + 'my_trigger'); + late final MyView myView = MyView(this); + Future writeConfig({required String key, required String value}) { + return customInsert( + 'REPLACE INTO config (config_key, config_value) VALUES (?1, ?2)', + variables: [Variable(key), Variable(value)], + updates: {}, + updateKind: UpdateKind.delete, + ); + } + + Selectable readConfig(String var1) { + return customSelect( + 'SELECT config_key AS ck, config_value AS cf, sync_state AS cs1, sync_state_implicit AS cs2 FROM config WHERE config_key = ?1', + variables: [ + Variable(var1) + ], + readsFrom: { + config, + }).asyncMap((QueryRow row) => config.mapFromRowWithAlias(row, const { + 'ck': 'config_key', + 'cf': 'config_value', + 'cs1': 'sync_state', + 'cs2': 'sync_state_implicit', + })); + } + + Selectable readMultiple(String var1, + {OrderBy clause = const OrderBy.nothing()}) { + var $arrayStartIndex = 2; + final generatedclause = $write(clause, startIndex: $arrayStartIndex); + $arrayStartIndex += generatedclause.amountOfVariables; + return customSelect( + 'SELECT * FROM config WHERE config_key IN ?1 ${generatedclause.sql}', + variables: [ + Variable(var1), + ...generatedclause.introducedVariables + ], + readsFrom: { + ...generatedclause.watchedTables, + }).map((QueryRow row) { + return ReadMultipleResult( + row: row, + ); + }); + } + + Selectable readDynamic({ReadDynamic$predicate? predicate}) { + var $arrayStartIndex = 1; + final generatedpredicate = $write( + predicate?.call(this.config) ?? const CustomExpression('(TRUE)'), + startIndex: $arrayStartIndex); + $arrayStartIndex += generatedpredicate.amountOfVariables; + return customSelect('SELECT * FROM config WHERE ${generatedpredicate.sql}', + variables: [ + ...generatedpredicate.introducedVariables + ], + readsFrom: { + config, + ...generatedpredicate.watchedTables, + }).asyncMap(config.mapFromRow); + } + + Selectable typeConverterVar(SyncType var1, List var2, + {TypeConverterVar$pred? pred}) { + var $arrayStartIndex = 2; + final generatedpred = $write( + pred?.call(this.config) ?? const CustomExpression('(TRUE)'), + startIndex: $arrayStartIndex); + $arrayStartIndex += generatedpred.amountOfVariables; + final expandedvar2 = $expandVar($arrayStartIndex, var2.length); + $arrayStartIndex += var2.length; + return customSelect( + 'SELECT config_key FROM config WHERE ${generatedpred.sql} AND(sync_state = ?1 OR sync_state_implicit IN ($expandedvar2))', + variables: [ + Variable($ConfigTable.$convertersyncStaten.toSql(var1)), + ...generatedpred.introducedVariables, + for (var $ in var2) + Variable($ConfigTable.$convertersyncStateImplicitn.toSql($)) + ], + readsFrom: { + config, + ...generatedpred.watchedTables, + }).map((QueryRow row) => row.read('config_key')); + } + + Selectable tableValued() { + return customSelect( + 'SELECT "key", value FROM config,json_each(config.config_value)WHERE json_valid(config_value)', + variables: [], + readsFrom: { + config, + }).map((QueryRow row) { + return TableValuedResult( + row: row, + key: row.read('key'), + value: row.readNullable('value'), + ); + }); + } + + Selectable another() { + return customSelect( + 'SELECT \'one\' AS "key", NULLIF(\'two\', \'another\') AS value', + variables: [], + readsFrom: {}).map((QueryRow row) { + return AnotherResult( + row: row, + key: row.read('key'), + value: row.readNullable('value'), + ); + }); + } + + Selectable multiple({required Multiple$predicate predicate}) { + var $arrayStartIndex = 1; + final generatedpredicate = $write( + predicate( + alias(this.withDefaults, 'd'), alias(this.withConstraints, 'c')), + hasMultipleTables: true, + startIndex: $arrayStartIndex); + $arrayStartIndex += generatedpredicate.amountOfVariables; + return customSelect( + 'SELECT d.*,"c"."a" AS "nested_0.a", "c"."b" AS "nested_0.b", "c"."c" AS "nested_0.c" FROM with_defaults AS d LEFT OUTER JOIN with_constraints AS c ON d.a = c.a AND d.b = c.b WHERE ${generatedpredicate.sql}', + variables: [ + ...generatedpredicate.introducedVariables + ], + readsFrom: { + withDefaults, + withConstraints, + ...generatedpredicate.watchedTables, + }).asyncMap((QueryRow row) async { + return MultipleResult( + row: row, + a: row.read('a'), + b: row.read('b'), + c: await withConstraints.mapFromRowOrNull(row, tablePrefix: 'nested_0'), + ); + }); + } + + Selectable searchEmails({required String? term}) { + return customSelect( + 'SELECT * FROM email WHERE email MATCH ?1 ORDER BY rank', + variables: [ + Variable(term) + ], + readsFrom: { + email, + }).asyncMap(email.mapFromRow); + } + + Selectable readRowId({required ReadRowId$expr expr}) { + var $arrayStartIndex = 1; + final generatedexpr = + $write(expr(this.config), startIndex: $arrayStartIndex); + $arrayStartIndex += generatedexpr.amountOfVariables; + return customSelect( + 'SELECT oid, * FROM config WHERE _rowid_ = ${generatedexpr.sql}', + variables: [ + ...generatedexpr.introducedVariables + ], + readsFrom: { + config, + ...generatedexpr.watchedTables, + }).map((QueryRow row) { + return ReadRowIdResult( + row: row, + rowid: row.read('rowid'), + configKey: row.read('config_key'), + configValue: row.read('config_value'), + syncState: $ConfigTable.$convertersyncStaten + .fromSql(row.read('sync_state')), + syncStateImplicit: $ConfigTable.$convertersyncStateImplicitn + .fromSql(row.read('sync_state_implicit')), + ); + }); + } + + Selectable readView() { + return customSelect('SELECT * FROM my_view', variables: [], readsFrom: { + config, + }).map((QueryRow row) { + return ReadViewResult( + row: row, + configKey: row.read('config_key'), + configValue: row.read('config_value'), + syncState: + MyView.$convertersyncStaten.fromSql(row.read('sync_state')), + syncStateImplicit: MyView.$convertersyncStateImplicitn + .fromSql(row.read('sync_state_implicit')), + ); + }); + } + + Selectable cfeTest() { + return customSelect( + 'WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM cnt LIMIT 1000000) SELECT x FROM cnt', + variables: [], + readsFrom: {}).map((QueryRow row) => row.read('x')); + } + + Selectable nullableQuery() { + return customSelect('SELECT MAX(oid) AS _c0 FROM config', + variables: [], + readsFrom: { + config, + }).map((QueryRow row) => row.readNullable('_c0')); + } + + Future> addConfig({required Insertable value}) { + var $arrayStartIndex = 1; + final generatedvalue = + $writeInsertable(this.config, value, startIndex: $arrayStartIndex); + $arrayStartIndex += generatedvalue.amountOfVariables; + return customWriteReturning( + 'INSERT INTO config ${generatedvalue.sql} RETURNING *', + variables: [...generatedvalue.introducedVariables], + updates: {config}) + .then((rows) => Future.wait(rows.map(config.mapFromRow))); + } + + Selectable nested(String var1) { + return customSelect( + 'SELECT"defaults"."a" AS "nested_0.a", "defaults"."b" AS "nested_0.b", defaults.b AS "\$n_0" FROM with_defaults AS defaults WHERE a = ?1', + variables: [ + Variable(var1) + ], + readsFrom: { + withConstraints, + withDefaults, + }).asyncMap((QueryRow row) async { + return NestedResult( + row: row, + defaults: await withDefaults.mapFromRow(row, tablePrefix: 'nested_0'), + nestedQuery0: await customSelect( + 'SELECT * FROM with_constraints AS c WHERE c.b = ?1', + variables: [ + Variable(row.read('\$n_0')) + ], + readsFrom: { + withConstraints, + withDefaults, + }).asyncMap(withConstraints.mapFromRow).get(), + ); + }); + } + + @override + Iterable> get allTables => + allSchemaEntities.whereType>(); + @override + List get allSchemaEntities => [ + noIds, + withDefaults, + withConstraints, + config, + valueIdx, + mytable, + email, + weirdTable, + myTrigger, + myView, + null, + null, + null, + null, + null, + null, + OnCreateQuery( + 'INSERT INTO config (config_key, config_value) VALUES (\'key\', \'values\')'), + null, + null, + null, + null, + null, + null, + null, + null + ]; + @override + DriftDatabaseOptions get options => + const DriftDatabaseOptions(storeDateTimeAsText: true); } -if (data.containsKey('body')) { -context.handle(_bodyMeta, body.isAcceptableOrUnknown(data['body']!, _bodyMeta));} else if (isInserting) { -context.missing(_bodyMeta); -} -return context; -} -@override -Set get $primaryKey => const {};@override EMail map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return EMail(sender: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}sender'])!, title: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}title'])!, body: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}body'])!, ); -} -@override -$EmailTable createAlias(String alias) { -return $EmailTable(attachedDatabase, alias);}@override -String get moduleAndArgs => 'fts5(sender, title, body)'; -}class WeirdData extends DataClass implements Insertable { -final int sqlClass; -final String textColumn; -const WeirdData({required this.sqlClass, required this.textColumn});@override -Map toColumns(bool nullToAbsent) { -final map = {};map['class'] = Variable(sqlClass);map['text'] = Variable(textColumn);return map; -} -WeirdTableCompanion toCompanion(bool nullToAbsent) { -return WeirdTableCompanion(sqlClass: Value (sqlClass),textColumn: Value (textColumn),); -} -factory WeirdData.fromJson(Map json, {ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return WeirdData(sqlClass: serializer.fromJson(json['class']),textColumn: serializer.fromJson(json['text']),);} -factory WeirdData.fromJsonString(String encodedJson, {ValueSerializer? serializer}) => WeirdData.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer);@override Map toJson({ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return { -'class': serializer.toJson(sqlClass),'text': serializer.toJson(textColumn),};}WeirdData copyWith({int? sqlClass,String? textColumn}) => WeirdData(sqlClass: sqlClass ?? this.sqlClass,textColumn: textColumn ?? this.textColumn,);@override -String toString() {return (StringBuffer('WeirdData(')..write('sqlClass: $sqlClass, ')..write('textColumn: $textColumn')..write(')')).toString();} -@override - int get hashCode => Object.hash(sqlClass, textColumn);@override -bool operator ==(Object other) => identical(this, other) || (other is WeirdData && other.sqlClass == this.sqlClass && other.textColumn == this.textColumn); -}class WeirdTableCompanion extends UpdateCompanion { -final Value sqlClass; -final Value textColumn; -const WeirdTableCompanion({this.sqlClass = const Value.absent(),this.textColumn = const Value.absent(),}); -WeirdTableCompanion.insert({required int sqlClass,required String textColumn,}): sqlClass = Value(sqlClass), textColumn = Value(textColumn); -static Insertable custom({Expression? sqlClass, -Expression? textColumn, -}) { -return RawValuesInsertable({if (sqlClass != null)'class': sqlClass,if (textColumn != null)'text': textColumn,}); -}WeirdTableCompanion copyWith({Value? sqlClass, Value? textColumn}) { -return WeirdTableCompanion(sqlClass: sqlClass ?? this.sqlClass,textColumn: textColumn ?? this.textColumn,); -} -@override -Map toColumns(bool nullToAbsent) { -final map = {};if (sqlClass.present) {map['class'] = Variable(sqlClass.value);}if (textColumn.present) {map['text'] = Variable(textColumn.value);}return map; -} -@override -String toString() {return (StringBuffer('WeirdTableCompanion(')..write('sqlClass: $sqlClass, ')..write('textColumn: $textColumn')..write(')')).toString();} -} -class $WeirdTableTable extends Table with TableInfo<$WeirdTableTable, WeirdData> { -@override final GeneratedDatabase attachedDatabase; -final String? _alias; -$WeirdTableTable(this.attachedDatabase, [this._alias]); -final VerificationMeta _sqlClassMeta = const VerificationMeta('sqlClass'); -late final GeneratedColumn sqlClass = GeneratedColumn('class', aliasedName, false, type: DriftSqlType.int, requiredDuringInsert: true); -final VerificationMeta _textColumnMeta = const VerificationMeta('textColumn'); -late final GeneratedColumn textColumn = GeneratedColumn('text', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); -@override -List get $columns => [sqlClass, textColumn]; -@override -String get aliasedName => _alias ?? 'Expression'; -@override - String get actualTableName => 'Expression'; -@override -VerificationContext validateIntegrity(Insertable instance, {bool isInserting = false}) { -final context = VerificationContext(); -final data = instance.toColumns(true); -if (data.containsKey('class')) { -context.handle(_sqlClassMeta, sqlClass.isAcceptableOrUnknown(data['class']!, _sqlClassMeta));} else if (isInserting) { -context.missing(_sqlClassMeta); -} -if (data.containsKey('text')) { -context.handle(_textColumnMeta, textColumn.isAcceptableOrUnknown(data['text']!, _textColumnMeta));} else if (isInserting) { -context.missing(_textColumnMeta); -} -return context; -} -@override -Set get $primaryKey => const {};@override WeirdData map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return WeirdData(sqlClass: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}class'])!, textColumn: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}text'])!, ); -} -@override -$WeirdTableTable createAlias(String alias) { -return $WeirdTableTable(attachedDatabase, alias);}}class MyViewData extends DataClass { -final String configKey; -final String configValue; -final int syncState; -final int syncStateImplicit; -const MyViewData({required this.configKey, required this.configValue, required this.syncState, required this.syncStateImplicit});factory MyViewData.fromJson(Map json, {ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return MyViewData(configKey: serializer.fromJson(json['config_key']),configValue: serializer.fromJson(json['config_value']),syncState: serializer.fromJson(json['sync_state']),syncStateImplicit: serializer.fromJson(json['sync_state_implicit']),);} -factory MyViewData.fromJsonString(String encodedJson, {ValueSerializer? serializer}) => MyViewData.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer);@override Map toJson({ValueSerializer? serializer}) { -serializer ??= driftRuntimeOptions.defaultSerializer; -return { -'config_key': serializer.toJson(configKey),'config_value': serializer.toJson(configValue),'sync_state': serializer.toJson(syncState),'sync_state_implicit': serializer.toJson(syncStateImplicit),};}MyViewData copyWith({String? configKey,String? configValue,int? syncState,int? syncStateImplicit}) => MyViewData(configKey: configKey ?? this.configKey,configValue: configValue ?? this.configValue,syncState: syncState ?? this.syncState,syncStateImplicit: syncStateImplicit ?? this.syncStateImplicit,);@override -String toString() {return (StringBuffer('MyViewData(')..write('configKey: $configKey, ')..write('configValue: $configValue, ')..write('syncState: $syncState, ')..write('syncStateImplicit: $syncStateImplicit')..write(')')).toString();} -@override - int get hashCode => Object.hash(configKey, configValue, syncState, syncStateImplicit);@override -bool operator ==(Object other) => identical(this, other) || (other is MyViewData && other.configKey == this.configKey && other.configValue == this.configValue && other.syncState == this.syncState && other.syncStateImplicit == this.syncStateImplicit); -}class MyView extends ViewInfo implements HasResultSet { -final String? _alias; -@override final _$CustomTablesDb attachedDatabase; -MyView(this.attachedDatabase, [this._alias]); -@override -List get $columns => [configKey, configValue, syncState, syncStateImplicit]; -@override -String get aliasedName => _alias ?? entityName; -@override - String get entityName=> 'my_view'; -@override -String get createViewStmt =>'CREATE VIEW my_view AS SELECT * FROM config WHERE sync_state = 2'@override -MyView get asDslTable => this; -@override MyViewData map(Map data, {String? tablePrefix}) { -final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';return MyViewData(configKey: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}config_key'])!, configValue: attachedDatabase.options.types.read(DriftSqlType.string, data['${effectivePrefix}config_value'])!, syncState: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}sync_state'])!, syncStateImplicit: attachedDatabase.options.types.read(DriftSqlType.int, data['${effectivePrefix}sync_state_implicit'])!, ); -} -late final GeneratedColumn configKey = GeneratedColumn('config_key', aliasedName, false, type: DriftSqlType.string); -late final GeneratedColumn configValue = GeneratedColumn('config_value', aliasedName, false, type: DriftSqlType.string); -late final GeneratedColumn syncState = GeneratedColumn('sync_state', aliasedName, false, type: DriftSqlType.int); -late final GeneratedColumn syncStateImplicit = GeneratedColumn('sync_state_implicit', aliasedName, false, type: DriftSqlType.int); -@override -MyView createAlias(String alias) { -return MyView(attachedDatabase, alias);}@override -Query? get query => null; - @override - Set get readTables => const {'config'}; - -} -abstract class _$CustomTablesDb extends GeneratedDatabase{ -_$CustomTablesDb(QueryExecutor e): super(e); -_$CustomTablesDb.connect(DatabaseConnection c): super.connect(c); -late final $NoIdsTable noIds = $NoIdsTable(this); -late final $WithDefaultsTable withDefaults = $WithDefaultsTable(this); -late final $WithConstraintsTable withConstraints = $WithConstraintsTable(this); -late final $ConfigTable config = $ConfigTable(this); -late final Index valueIdx = Index('value_idx', 'CREATE INDEX IF NOT EXISTS value_idx ON config (config_value)'); -late final $MytableTable mytable = $MytableTable(this); -late final $EmailTable email = $EmailTable(this); -late final $WeirdTableTable weirdTable = $WeirdTableTable(this); -late final Trigger myTrigger = Trigger('CREATE TRIGGER my_trigger AFTER INSERT ON config BEGIN INSERT INTO with_defaults VALUES (new.config_key, LENGTH(new.config_value));END', 'my_trigger'); -late final MyView myView = MyView(this); -Future writeConfig({required String key, required String value}) { -return customInsert('REPLACE INTO config (config_key, config_value) VALUES (?1, ?2)',variables: [Variable(key), Variable(value)],updates: {}, updateKind: UpdateKind.delete,); -} -Selectable readConfig(String var1) { -return customSelect('SELECT config_key AS ck, config_value AS cf, sync_state AS cs1, sync_state_implicit AS cs2 FROM config WHERE config_key = ?1', variables: [Variable(var1)], readsFrom: {config,}).asyncMap((QueryRow row) => config.mapFromRowWithAlias(row, const {'ck': 'config_key', 'cf': 'config_value', 'cs1': 'sync_state', 'cs2': 'sync_state_implicit', })); -} -Selectable readMultiple(String var1, {OrderBy clause = const OrderBy.nothing()}) { -var $arrayStartIndex = 2;final generatedclause = $write(clause, startIndex: $arrayStartIndex); -$arrayStartIndex += generatedclause.amountOfVariables; -return customSelect('SELECT * FROM config WHERE config_key IN ?1 ${generatedclause.sql}', variables: [Variable(var1), ...generatedclause.introducedVariables], readsFrom: {...generatedclause.watchedTables,}).map((QueryRow row) { return ReadMultipleResult(row: row, -); -}); -} -Selectable readDynamic({ReadDynamic$predicate? predicate}) { -var $arrayStartIndex = 1;final generatedpredicate = $write(predicate?.call(this.config) ?? const CustomExpression('(TRUE)'), startIndex: $arrayStartIndex); -$arrayStartIndex += generatedpredicate.amountOfVariables; -return customSelect('SELECT * FROM config WHERE ${generatedpredicate.sql}', variables: [...generatedpredicate.introducedVariables], readsFrom: {config,...generatedpredicate.watchedTables,}).asyncMap(config.mapFromRow); -} -Selectable typeConverterVar(int var1, List var2, {TypeConverterVar$pred? pred}) { -var $arrayStartIndex = 2;final generatedpred = $write(pred?.call(this.config) ?? const CustomExpression('(TRUE)'), startIndex: $arrayStartIndex); -$arrayStartIndex += generatedpred.amountOfVariables; -final expandedvar2 = $expandVar($arrayStartIndex, var2.length); -$arrayStartIndex += var2.length; -return customSelect('SELECT config_key FROM config WHERE ${generatedpred.sql} AND(sync_state = ?1 OR sync_state_implicit IN ($expandedvar2))', variables: [Variable(var1), ...generatedpred.introducedVariables, for (var $ in var2) Variable($)], readsFrom: {config,...generatedpred.watchedTables,}).map((QueryRow row) => row.read('config_key')); -} -Selectable tableValued() { -return customSelect('SELECT "key", value FROM config,json_each(config.config_value)WHERE json_valid(config_value)', variables: [], readsFrom: {config,}).map((QueryRow row) { return TableValuedResult(row: row, -key: row.read('key'),value: row.readNullable('value'),); -}); -} -Selectable another() { -return customSelect('SELECT \'one\' AS "key", NULLIF(\'two\', \'another\') AS value', variables: [], readsFrom: {}).map((QueryRow row) { return AnotherResult(row: row, -key: row.read('key'),value: row.readNullable('value'),); -}); -} -Future special:0() { -return customInsert('INSERT INTO config (config_key, config_value) VALUES (\'key\', \'values\')',variables: [],updates: {config},); -} -Selectable multiple({required Multiple$predicate predicate}) { -var $arrayStartIndex = 1;final generatedpredicate = $write(predicate(alias(this.withDefaults, 'd'), alias(this.withConstraints, 'c')), hasMultipleTables: true, startIndex: $arrayStartIndex); -$arrayStartIndex += generatedpredicate.amountOfVariables; -return customSelect('SELECT d.*,"c"."a" AS "nested_0.a", "c"."b" AS "nested_0.b", "c"."c" AS "nested_0.c" FROM with_defaults AS d LEFT OUTER JOIN with_constraints AS c ON d.a = c.a AND d.b = c.b WHERE ${generatedpredicate.sql}', variables: [...generatedpredicate.introducedVariables], readsFrom: {withDefaults,withConstraints,...generatedpredicate.watchedTables,}).asyncMap((QueryRow row) async { return MultipleResult(row: row, -a: row.read('a'),b: row.read('b'),c: await withConstraints.mapFromRowOrNull(row, tablePrefix: 'nested_0'),); -}); -} -Selectable searchEmails({required String? term}) { -return customSelect('SELECT * FROM email WHERE email MATCH ?1 ORDER BY rank', variables: [Variable(term)], readsFrom: {email,}).asyncMap(email.mapFromRow); -} -Selectable readRowId({required ReadRowId$expr expr}) { -var $arrayStartIndex = 1;final generatedexpr = $write(expr(this.config), startIndex: $arrayStartIndex); -$arrayStartIndex += generatedexpr.amountOfVariables; -return customSelect('SELECT oid, * FROM config WHERE _rowid_ = ${generatedexpr.sql}', variables: [...generatedexpr.introducedVariables], readsFrom: {config,...generatedexpr.watchedTables,}).map((QueryRow row) { return ReadRowIdResult(row: row, -rowid: row.read('rowid'),configKey: row.read('config_key'),configValue: row.read('config_value'),syncState: row.read('sync_state'),syncStateImplicit: row.read('sync_state_implicit'),); -}); -} -Selectable readView() { -return customSelect('SELECT * FROM my_view', variables: [], readsFrom: {config,}).map((QueryRow row) { return ReadViewResult(row: row, -configKey: row.read('config_key'),configValue: row.read('config_value'),syncState: row.read('sync_state'),syncStateImplicit: row.read('sync_state_implicit'),); -}); -} -Selectable cfeTest() { -return customSelect('WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM cnt LIMIT 1000000) SELECT x FROM cnt', variables: [], readsFrom: {}).map((QueryRow row) => row.read('x')); -} -Selectable nullableQuery() { -return customSelect('SELECT MAX(oid) AS _c0 FROM config', variables: [], readsFrom: {config,}).map((QueryRow row) => row.readNullable('_c0')); -} -Future> addConfig({required Insertable value}) { -var $arrayStartIndex = 1;final generatedvalue = $writeInsertable(this.config, value, startIndex: $arrayStartIndex); -$arrayStartIndex += generatedvalue.amountOfVariables; -return customWriteReturning('INSERT INTO config ${generatedvalue.sql} RETURNING *',variables: [...generatedvalue.introducedVariables],updates: {config}).then((rows) => Future.wait(rows.map(config.mapFromRow))); -}Selectable nested(String var1) { -return customSelect('SELECT"defaults"."a" AS "nested_0.a", "defaults"."b" AS "nested_0.b", defaults.b AS "\$n_0" FROM with_defaults AS defaults WHERE a = ?1', variables: [Variable(var1)], readsFrom: {withConstraints,withDefaults,}).asyncMap((QueryRow row) async { return NestedResult(row: row, -defaults: await withDefaults.mapFromRow(row, tablePrefix: 'nested_0'),nestedQuery0: await customSelect('SELECT * FROM with_constraints AS c WHERE c.b = ?1', variables: [Variable(row.read('\$n_0'))], readsFrom: {withConstraints,withDefaults,}).asyncMap(withConstraints.mapFromRow).get(),); -}); -} -@override -Iterable> get allTables => allSchemaEntities.whereType>(); -@override -List get allSchemaEntities => []; -@override -DriftDatabaseOptions get options => const DriftDatabaseOptions(storeDateTimeAsText: true); -} -typedef ReadDynamic$predicate = Expression Function($ConfigTable config);typedef TypeConverterVar$pred = Expression Function($ConfigTable config);class TableValuedResult extends CustomResultSet { -final String key -;final String? value -;TableValuedResult({required QueryRow row,required this.key,this.value,}): super(row); -@override int get hashCode => Object.hash(key, value); -@override -bool operator ==(Object other) => identical(this, other) || (other is TableValuedResult && other.key == this.key && other.value == this.value); -@override -String toString() {return (StringBuffer('TableValuedResult(')..write('key: $key, ')..write('value: $value')..write(')')).toString();} + +typedef ReadDynamic$predicate = Expression Function($ConfigTable config); +typedef TypeConverterVar$pred = Expression Function($ConfigTable config); + +class TableValuedResult extends CustomResultSet { + final String key; + final String? value; + TableValuedResult({ + required QueryRow row, + required this.key, + this.value, + }) : super(row); + @override + int get hashCode => Object.hash(key, value); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is TableValuedResult && + other.key == this.key && + other.value == this.value); + @override + String toString() { + return (StringBuffer('TableValuedResult(') + ..write('key: $key, ') + ..write('value: $value') + ..write(')')) + .toString(); + } } + class AnotherResult extends CustomResultSet { -final String key -;final String? value -;AnotherResult({required QueryRow row,required this.key,this.value,}): super(row); -@override int get hashCode => Object.hash(key, value); -@override -bool operator ==(Object other) => identical(this, other) || (other is AnotherResult && other.key == this.key && other.value == this.value); -@override -String toString() {return (StringBuffer('AnotherResult(')..write('key: $key, ')..write('value: $value')..write(')')).toString();} + final String key; + final String? value; + AnotherResult({ + required QueryRow row, + required this.key, + this.value, + }) : super(row); + @override + int get hashCode => Object.hash(key, value); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is AnotherResult && + other.key == this.key && + other.value == this.value); + @override + String toString() { + return (StringBuffer('AnotherResult(') + ..write('key: $key, ') + ..write('value: $value') + ..write(')')) + .toString(); + } } + class MultipleResult extends CustomResultSet { -final String a -;final int b -;final WithConstraint? c; -MultipleResult({required QueryRow row,required this.a,required this.b,this.c,}): super(row); -@override int get hashCode => Object.hash(a, b, c); -@override -bool operator ==(Object other) => identical(this, other) || (other is MultipleResult && other.a == this.a && other.b == this.b && other.c == this.c); -@override -String toString() {return (StringBuffer('MultipleResult(')..write('a: $a, ')..write('b: $b, ')..write('c: $c')..write(')')).toString();} + final String a; + final int b; + final WithConstraint? c; + MultipleResult({ + required QueryRow row, + required this.a, + required this.b, + this.c, + }) : super(row); + @override + int get hashCode => Object.hash(a, b, c); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is MultipleResult && + other.a == this.a && + other.b == this.b && + other.c == this.c); + @override + String toString() { + return (StringBuffer('MultipleResult(') + ..write('a: $a, ') + ..write('b: $b, ') + ..write('c: $c') + ..write(')')) + .toString(); + } } -typedef Multiple$predicate = Expression Function($WithDefaultsTable d, $WithConstraintsTable c);class ReadRowIdResult extends CustomResultSet { -final int rowid -;final String configKey -;final String configValue -;final int syncState -;final int syncStateImplicit -;ReadRowIdResult({required QueryRow row,required this.rowid,required this.configKey,required this.configValue,required this.syncState,required this.syncStateImplicit,}): super(row); -@override int get hashCode => Object.hash(rowid, configKey, configValue, syncState, syncStateImplicit); -@override -bool operator ==(Object other) => identical(this, other) || (other is ReadRowIdResult && other.rowid == this.rowid && other.configKey == this.configKey && other.configValue == this.configValue && other.syncState == this.syncState && other.syncStateImplicit == this.syncStateImplicit); -@override -String toString() {return (StringBuffer('ReadRowIdResult(')..write('rowid: $rowid, ')..write('configKey: $configKey, ')..write('configValue: $configValue, ')..write('syncState: $syncState, ')..write('syncStateImplicit: $syncStateImplicit')..write(')')).toString();} + +typedef Multiple$predicate = Expression Function( + $WithDefaultsTable d, $WithConstraintsTable c); + +class ReadRowIdResult extends CustomResultSet { + final int rowid; + final String configKey; + final String configValue; + final SyncType syncState; + final SyncType syncStateImplicit; + ReadRowIdResult({ + required QueryRow row, + required this.rowid, + required this.configKey, + required this.configValue, + required this.syncState, + required this.syncStateImplicit, + }) : super(row); + @override + int get hashCode => + Object.hash(rowid, configKey, configValue, syncState, syncStateImplicit); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is ReadRowIdResult && + other.rowid == this.rowid && + other.configKey == this.configKey && + other.configValue == this.configValue && + other.syncState == this.syncState && + other.syncStateImplicit == this.syncStateImplicit); + @override + String toString() { + return (StringBuffer('ReadRowIdResult(') + ..write('rowid: $rowid, ') + ..write('configKey: $configKey, ') + ..write('configValue: $configValue, ') + ..write('syncState: $syncState, ') + ..write('syncStateImplicit: $syncStateImplicit') + ..write(')')) + .toString(); + } } -typedef ReadRowId$expr = Expression Function($ConfigTable config);class ReadViewResult extends CustomResultSet { -final String configKey -;final String configValue -;final int syncState -;final int syncStateImplicit -;ReadViewResult({required QueryRow row,required this.configKey,required this.configValue,required this.syncState,required this.syncStateImplicit,}): super(row); -@override int get hashCode => Object.hash(configKey, configValue, syncState, syncStateImplicit); -@override -bool operator ==(Object other) => identical(this, other) || (other is ReadViewResult && other.configKey == this.configKey && other.configValue == this.configValue && other.syncState == this.syncState && other.syncStateImplicit == this.syncStateImplicit); -@override -String toString() {return (StringBuffer('ReadViewResult(')..write('configKey: $configKey, ')..write('configValue: $configValue, ')..write('syncState: $syncState, ')..write('syncStateImplicit: $syncStateImplicit')..write(')')).toString();} + +typedef ReadRowId$expr = Expression Function($ConfigTable config); + +class ReadViewResult extends CustomResultSet { + final String configKey; + final String configValue; + final SyncType syncState; + final SyncType syncStateImplicit; + ReadViewResult({ + required QueryRow row, + required this.configKey, + required this.configValue, + required this.syncState, + required this.syncStateImplicit, + }) : super(row); + @override + int get hashCode => + Object.hash(configKey, configValue, syncState, syncStateImplicit); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is ReadViewResult && + other.configKey == this.configKey && + other.configValue == this.configValue && + other.syncState == this.syncState && + other.syncStateImplicit == this.syncStateImplicit); + @override + String toString() { + return (StringBuffer('ReadViewResult(') + ..write('configKey: $configKey, ') + ..write('configValue: $configValue, ') + ..write('syncState: $syncState, ') + ..write('syncStateImplicit: $syncStateImplicit') + ..write(')')) + .toString(); + } } + class NestedResult extends CustomResultSet { -final WithDefault defaults; -finalListnestedQuery0; -NestedResult({required QueryRow row,required this.defaults,required this.nestedQuery0,}): super(row); -@override int get hashCode => Object.hash(defaults, nestedQuery0); -@override -bool operator ==(Object other) => identical(this, other) || (other is NestedResult && other.defaults == this.defaults && other.nestedQuery0 == this.nestedQuery0); -@override -String toString() {return (StringBuffer('NestedResult(')..write('defaults: $defaults, ')..write('nestedQuery0: $nestedQuery0')..write(')')).toString();} + final WithDefault defaults; + finalList nestedQuery0; + NestedResult({ + required QueryRow row, + required this.defaults, + required this.nestedQuery0, + }) : super(row); + @override + int get hashCode => Object.hash(defaults, nestedQuery0); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is NestedResult && + other.defaults == this.defaults && + other.nestedQuery0 == this.nestedQuery0); + @override + String toString() { + return (StringBuffer('NestedResult(') + ..write('defaults: $defaults, ') + ..write('nestedQuery0: $nestedQuery0') + ..write(')')) + .toString(); + } } diff --git a/drift/test/generated/todos.g.dart b/drift/test/generated/todos.g.dart index f9fa1ae1..a9e675f6 100644 --- a/drift/test/generated/todos.g.dart +++ b/drift/test/generated/todos.g.dart @@ -1730,8 +1730,27 @@ class AllTodosWithCategoryResult extends CustomResultSet { .toString(); } } + // DriftElementId(asset:drift/test/generated/todos.dart, users) // DriftElementId(asset:drift/test/generated/todos.dart, shared_todos) // DriftElementId(asset:drift/test/generated/todos.dart, table_without_p_k) // DriftElementId(asset:drift/test/generated/todos.dart, pure_defaults) -// DriftElementId(asset:drift/test/generated/todos.dart, SomeDao) +mixin _$SomeDaoMixin on DatabaseAccessor { + $UsersTable get users => attachedDatabase.users; + $SharedTodosTable get sharedTodos => attachedDatabase.sharedTodos; + $TodosTableTable get todosTable => attachedDatabase.todosTable; + $TodoWithCategoryViewView get todoWithCategoryView => + attachedDatabase.todoWithCategoryView; + Selectable todosForUser({required int user}) { + return customSelect( + 'SELECT t.* FROM todos AS t INNER JOIN shared_todos AS st ON st.todo = t.id INNER JOIN users AS u ON u.id = st.user WHERE u.id = ?1', + variables: [ + Variable(user) + ], + readsFrom: { + todosTable, + sharedTodos, + users, + }).asyncMap(todosTable.mapFromRow); + } +} diff --git a/drift_dev/lib/src/analysis/backend.dart b/drift_dev/lib/src/analysis/backend.dart index 3c3b4f97..2c551ab2 100644 --- a/drift_dev/lib/src/analysis/backend.dart +++ b/drift_dev/lib/src/analysis/backend.dart @@ -15,6 +15,17 @@ abstract class DriftBackend { Future readDart(Uri uri); Future loadElementDeclaration(Element element); + + /// Resolves a Dart expression from a string. + /// + /// [context] is a file in which the expression should be resolved, which is + /// relevant for relevant imports. [imports] is a list of (relative) imports + /// which may be used to resolve the expression. + /// + /// Throws a [CannotReadExpressionException] if the type could not be + /// resolved. + Future resolveExpression( + Uri context, String dartExpression, Iterable imports); } /// Thrown when attempting to read a Dart library from a file that's not a @@ -25,3 +36,14 @@ class NotALibraryException implements Exception { NotALibraryException(this.uri); } + +class CannotReadExpressionException implements Exception { + final String msg; + + CannotReadExpressionException(this.msg); + + @override + String toString() { + return 'Could not read expression: $msg'; + } +} diff --git a/drift_dev/lib/src/analysis/resolver/drift/query.dart b/drift_dev/lib/src/analysis/resolver/drift/query.dart index e671c38f..2cf6dcf6 100644 --- a/drift_dev/lib/src/analysis/resolver/drift/query.dart +++ b/drift_dev/lib/src/analysis/resolver/drift/query.dart @@ -1,3 +1,5 @@ +import 'package:sqlparser/sqlparser.dart'; + import '../../driver/state.dart'; import '../../results/results.dart'; import '../intermediate_state.dart'; @@ -14,6 +16,9 @@ class DriftQueryResolver final source = (file.discovery as DiscoveredDriftFile).originalSource; + final isCreate = + discovered.sqlNode.identifier is SpecialStatementIdentifier; + // Note: We don't analyze the query here, that happens in // `file_analysis.dart` after elements have been resolved. return DefinedSqlQuery( @@ -22,6 +27,7 @@ class DriftQueryResolver references: references, sql: source.substring(stmt.firstPosition, stmt.lastPosition), sqlOffset: stmt.firstPosition, + mode: isCreate ? QueryMode.atCreate : QueryMode.regular, ); } } diff --git a/drift_dev/lib/src/analysis/resolver/drift/table.dart b/drift_dev/lib/src/analysis/resolver/drift/table.dart index c56fae3a..83f1668d 100644 --- a/drift_dev/lib/src/analysis/resolver/drift/table.dart +++ b/drift_dev/lib/src/analysis/resolver/drift/table.dart @@ -1,7 +1,10 @@ +import 'package:analyzer/dart/ast/ast.dart' as dart; import 'package:collection/collection.dart'; +import 'package:drift/drift.dart' show DriftSqlType; import 'package:recase/recase.dart'; import 'package:sqlparser/sqlparser.dart'; +import '../../backend.dart'; import '../../driver/error.dart'; import '../../results/results.dart'; import '../intermediate_state.dart'; @@ -11,6 +14,9 @@ import '../shared/data_class.dart'; import 'find_dart_class.dart'; class DriftTableResolver extends LocalElementResolver { + static final RegExp _enumRegex = + RegExp(r'^enum\((\w+)\)$', caseSensitive: false); + DriftTableResolver(super.file, super.discovered, super.resolver, super.state); @override @@ -43,7 +49,32 @@ class DriftTableResolver extends LocalElementResolver { for (final column in table.resultColumns) { String? overriddenDartName; final type = resolver.driver.typeMapping.sqlTypeToDrift(column.type); + final nullable = column.type.nullable != false; final constraints = []; + AppliedTypeConverter? converter; + + final typeName = column.definition?.typeName; + final enumMatch = + typeName != null ? _enumRegex.firstMatch(typeName) : null; + if (enumMatch != null) { + final dartTypeName = enumMatch.group(1)!; + final imports = file.discovery!.importDependencies.toList(); + final dartClass = await findDartClass(imports, dartTypeName); + + if (dartClass == null) { + reportError(DriftAnalysisError.inDriftFile( + column.definition!.typeNames!.toSingleEntity, + 'Type $dartTypeName could not be found. Are you missing ' + 'an import?', + )); + } else { + converter = readEnumConverter( + (msg) => + DriftAnalysisError.inDriftFile(column.definition ?? stmt, msg), + dartClass.classElement.thisType, + ); + } + } // columns from virtual tables don't necessarily have a definition, so we // can't read the constraints. @@ -52,6 +83,16 @@ class DriftTableResolver extends LocalElementResolver { for (final constraint in sqlConstraints) { if (constraint is DriftDartName) { overriddenDartName = constraint.dartName; + } else if (constraint is MappedBy) { + if (converter != null) { + reportError(DriftAnalysisError.inDriftFile( + constraint, + 'Multiple type converters applied to this converter, ignoring ' + 'this one.')); + continue; + } + + converter = await _readTypeConverter(type, nullable, constraint); } else if (constraint is ForeignKeyColumnConstraint) { // Note: Warnings about whether the referenced column exists or not // are reported later, we just need to know dependencies before the @@ -89,10 +130,11 @@ class DriftTableResolver extends LocalElementResolver { columns.add(DriftColumn( sqlType: type, - nullable: column.type.nullable != false, + nullable: nullable, nameInSql: column.name, nameInDart: overriddenDartName ?? ReCase(column.name).camelCase, constraints: constraints, + typeConverter: converter, declaration: DriftDeclaration.driftFile( column.definition?.nameToken ?? stmt, state.ownId.libraryUri, @@ -196,4 +238,33 @@ class DriftTableResolver extends LocalElementResolver { virtualTableData: virtualTableData, ); } + + Future _readTypeConverter( + DriftSqlType sqlType, bool nullable, MappedBy mapper) async { + final code = mapper.mapper.dartCode; + + dart.Expression expression; + try { + expression = await resolver.driver.backend.resolveExpression( + file.ownUri, + code, + file.discovery!.importDependencies + .map((e) => e.toString()) + .where((e) => e.endsWith('.dart')), + ); + } on CannotReadExpressionException catch (e) { + reportError(DriftAnalysisError.inDriftFile(mapper, e.msg)); + return null; + } + + final knownTypes = await resolver.driver.loadKnownTypes(); + return readTypeConverter( + knownTypes.helperLibrary, + expression, + sqlType, + nullable, + (msg) => reportError(DriftAnalysisError.inDriftFile(mapper, msg)), + knownTypes, + ); + } } diff --git a/drift_dev/lib/src/analysis/results/query.dart b/drift_dev/lib/src/analysis/results/query.dart index 5509df7a..2568e664 100644 --- a/drift_dev/lib/src/analysis/results/query.dart +++ b/drift_dev/lib/src/analysis/results/query.dart @@ -32,6 +32,7 @@ class DefinedSqlQuery extends DriftElement implements DriftQueryDeclaration { final String sql; final String? resultClassName; + final QueryMode mode; /// The offset of [sql] in the source file, used to properly report errors /// later. @@ -50,9 +51,15 @@ class DefinedSqlQuery extends DriftElement implements DriftQueryDeclaration { required this.sql, required this.sqlOffset, this.resultClassName, + this.mode = QueryMode.regular, }); } +enum QueryMode { + regular, + atCreate, +} + /// A fully-resolved and analyzed SQL query. abstract class SqlQuery { final String name; diff --git a/drift_dev/lib/src/analysis/serializer.dart b/drift_dev/lib/src/analysis/serializer.dart index 5fea2df2..233e39fd 100644 --- a/drift_dev/lib/src/analysis/serializer.dart +++ b/drift_dev/lib/src/analysis/serializer.dart @@ -55,6 +55,7 @@ class ElementSerializer { 'sql': element.sql, 'offset': element.sqlOffset, 'result_class': element.resultClassName, + 'mode': element.mode.name, }; } else if (element is DriftTrigger) { additionalInformation = { @@ -462,6 +463,7 @@ class ElementDeserializer { sql: json['sql'] as String, sqlOffset: json['offset'] as int, resultClassName: json['result_class'] as String?, + mode: QueryMode.values.byName(json['mode'] as String), ); case 'trigger': DriftTable? on; diff --git a/drift_dev/lib/src/backends/build/backend.dart b/drift_dev/lib/src/backends/build/backend.dart index fe085e1c..6a2efa01 100644 --- a/drift_dev/lib/src/backends/build/backend.dart +++ b/drift_dev/lib/src/backends/build/backend.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:logging/logging.dart'; @@ -6,6 +8,7 @@ import 'package:build/build.dart' as build; import '../../analysis/backend.dart'; import '../../analysis/driver/driver.dart'; +import '../../analysis/preprocess_drift.dart'; class DriftBuildBackend extends DriftBackend { final BuildStep _buildStep; @@ -52,6 +55,42 @@ class DriftBuildBackend extends DriftBackend { Future loadElementDeclaration(Element element) { return _buildStep.resolver.astNodeFor(element, resolve: true); } + + @override + Future resolveExpression( + Uri context, String dartExpression, Iterable imports) async { + final original = AssetId.resolve(context); + final tempDart = original.changeExtension('.temp.dart'); + final prepJson = original.changeExtension('.drift_prep.json'); + + DriftPreprocessorResult prepResult; + try { + prepResult = DriftPreprocessorResult.fromJson( + json.decode(await _buildStep.readAsString(prepJson)) + as Map); + } on Exception catch (e, s) { + log.warning('Could not read Dart expression $dartExpression', e, s); + throw CannotReadExpressionException('Could not load helpers'); + } + + final getter = + prepResult.inlineDartExpressionsToHelperField[dartExpression]; + if (getter == null) { + throw CannotReadExpressionException('No field for $dartExpression'); + } + + final library = await _buildStep.resolver.libraryFor(tempDart); + final field = library.units.first.topLevelVariables + .firstWhere((element) => element.name == getter); + final fieldAst = await _buildStep.resolver.astNodeFor(field, resolve: true); + + final initializer = (fieldAst as VariableDeclaration).initializer; + if (initializer == null) { + throw CannotReadExpressionException( + 'Malformed helper file, this should never happen'); + } + return initializer; + } } class BuildCacheReader implements AnalysisResultCacheReader { diff --git a/drift_dev/lib/src/backends/build/drift_builder.dart b/drift_dev/lib/src/backends/build/drift_builder.dart index b358e9cb..a8d70521 100644 --- a/drift_dev/lib/src/backends/build/drift_builder.dart +++ b/drift_dev/lib/src/backends/build/drift_builder.dart @@ -5,6 +5,7 @@ import '../../analysis/driver/driver.dart'; import '../../analysis/results/results.dart'; import '../../analyzer/options.dart'; import '../../writer/database_writer.dart'; +import '../../writer/drift_accessor_writer.dart'; import '../../writer/import_manager.dart'; import '../../writer/writer.dart'; import 'backend.dart'; @@ -88,22 +89,30 @@ class DriftBuilder extends Builder { for (final element in fileResult.analysis.values) { final result = element.result; - if (result is DriftDatabase) { - final importedQueries = {}; + if (result is BaseDriftAccessor) { final resolved = fileResult.fileAnalysis!.resolvedDatabases[result.id]!; + final importedQueries = {}; - // Crawl queries - for (final imported in driver.cache.crawlMulti(resolved.knownImports)) { - final resolved = await driver.fullyAnalyze(imported.ownUri); - importedQueries.addAll({ - for (final entry in resolved.fileAnalysis!.resolvedQueries.entries) - entry.key.name: entry.value, - }); + for (final query + in resolved.availableElements.whereType()) { + final resolvedFile = await driver.fullyAnalyze(query.id.libraryUri); + final resolvedQuery = + resolvedFile.fileAnalysis?.resolvedQueries[query.id]; + + if (resolvedQuery != null) { + importedQueries[query] = resolvedQuery; + } } - final input = DatabaseGenerationInput( - result, resolved, importedQueries.values.toList()); - DatabaseWriter(input, writer.child()).write(); + if (result is DriftDatabase) { + final input = + DatabaseGenerationInput(result, resolved, importedQueries); + DatabaseWriter(input, writer.child()).write(); + } else if (result is DatabaseAccessor) { + final input = + AccessorGenerationInput(result, resolved, importedQueries); + AccessorWriter(input, writer.child()).write(); + } } else { writer.leaf().writeln('// ${element.ownId}'); } diff --git a/drift_dev/lib/src/writer/database_writer.dart b/drift_dev/lib/src/writer/database_writer.dart index 0fa59324..f935d9ae 100644 --- a/drift_dev/lib/src/writer/database_writer.dart +++ b/drift_dev/lib/src/writer/database_writer.dart @@ -19,7 +19,7 @@ class DatabaseWriter { DatabaseGenerationInput input; final Scope scope; - DriftDatabase get db => input.db; + DriftDatabase get db => input.accessor; DatabaseWriter(this.input, this.scope); @@ -127,9 +127,7 @@ class DatabaseWriter { } // Write implementation for query methods - final queries = input.resolvedAccessor.definedQueries.values - .followedBy(input.importedQueries); - for (final query in queries) { + for (final query in input.availableRegularQueries) { QueryWriter(dbScope.child()).write(query); } @@ -144,11 +142,13 @@ class DatabaseWriter { ..write('=> ['); schemaScope - ..write(db.references.map((e) { -// if (e is SpecialQuery) { -// final sql = e.formattedSql(scope.options); -// return 'OnCreateQuery(${asDartLiteral(sql)})'; -// } + ..write(elements.map((e) { + if (e is DefinedSqlQuery && e.mode == QueryMode.atCreate) { + final resolved = input.importedQueries[e]!; + final sql = schemaScope.sqlCode(resolved.root!); + + return 'OnCreateQuery(${asDartLiteral(sql)})'; + } return entityGetters[e]; }).join(', ')) @@ -192,15 +192,26 @@ class DatabaseWriter { } } -class DatabaseGenerationInput { - final DriftDatabase db; +class GenerationInput { + final T accessor; final ResolvedDatabaseAccessor resolvedAccessor; + final Map importedQueries; - final List importedQueries; + GenerationInput(this.accessor, this.resolvedAccessor, this.importedQueries); - DatabaseGenerationInput(this.db, this.resolvedAccessor, this.importedQueries); + /// All locally-defined and imported [SqlQuery] elements that are regular + /// queries (so no query with [QueryMode.atCreate]). + Iterable get availableRegularQueries { + final imported = importedQueries.entries + .where((entry) => entry.key.mode == QueryMode.regular) + .map((e) => e.value); + return resolvedAccessor.definedQueries.values.followedBy(imported); + } } +typedef DatabaseGenerationInput = GenerationInput; +typedef AccessorGenerationInput = GenerationInput; + extension on drift.UpdateRule { void writeConstructor(TextEmitter emitter) { if (this is drift.WritePropagation) { diff --git a/drift_dev/lib/src/writer/drift_accessor_writer.dart b/drift_dev/lib/src/writer/drift_accessor_writer.dart new file mode 100644 index 00000000..c76a4018 --- /dev/null +++ b/drift_dev/lib/src/writer/drift_accessor_writer.dart @@ -0,0 +1,34 @@ +import '../analysis/results/results.dart'; +import 'database_writer.dart'; +import 'queries/query_writer.dart'; +import 'writer.dart'; + +class AccessorWriter { + final AccessorGenerationInput input; + final Scope scope; + + AccessorWriter(this.input, this.scope); + + void write() { + final classScope = scope.child(); + + final daoName = input.accessor.declaration.name!; + final dbTypeName = classScope.dartCode(input.accessor.databaseClass); + classScope.leaf().write('mixin _\$${daoName}Mixin on ' + 'DatabaseAccessor<$dbTypeName> {\n'); + + for (final entity in input.resolvedAccessor.availableElements + .whereType()) { + final infoType = entity.entityInfoName; + final getterName = entity.dbGetterName; + classScope.leaf().write( + '$infoType get $getterName => attachedDatabase.$getterName;\n'); + } + + for (final query in input.availableRegularQueries) { + QueryWriter(classScope.child()).write(query); + } + + classScope.leaf().write('}'); + } +} diff --git a/drift_dev/lib/src/writer/tables/view_writer.dart b/drift_dev/lib/src/writer/tables/view_writer.dart index fb9f97db..48f3c70f 100644 --- a/drift_dev/lib/src/writer/tables/view_writer.dart +++ b/drift_dev/lib/src/writer/tables/view_writer.dart @@ -81,6 +81,7 @@ class ViewWriter extends TableOrViewWriter { } else { emitter.write(asDartLiteral(source.createView)); } + buffer.writeln(';'); } else { buffer.write('@override\n String? get createViewStmt => null;\n'); }