Fix writing type converters

This commit is contained in:
Simon Binder 2022-11-01 00:14:17 +01:00
parent fe3566429f
commit c2b319bc8e
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
10 changed files with 161 additions and 148 deletions

View File

@ -50,7 +50,9 @@ class $NoIdsTable extends Table with TableInfo<$NoIdsTable, NoIdRow> {
final VerificationMeta _payloadMeta = const VerificationMeta('payload'); final VerificationMeta _payloadMeta = const VerificationMeta('payload');
late final GeneratedColumn<Uint8List> payload = GeneratedColumn<Uint8List>( late final GeneratedColumn<Uint8List> payload = GeneratedColumn<Uint8List>(
'payload', aliasedName, false, 'payload', aliasedName, false,
type: DriftSqlType.blob, requiredDuringInsert: true); type: DriftSqlType.blob,
requiredDuringInsert: true,
defaultConstraints: 'PRIMARY KEY');
@override @override
List<GeneratedColumn> get $columns => [payload]; List<GeneratedColumn> get $columns => [payload];
@override @override
@ -72,7 +74,7 @@ class $NoIdsTable extends Table with TableInfo<$NoIdsTable, NoIdRow> {
} }
@override @override
Set<GeneratedColumn> get $primaryKey => const <GeneratedColumn>{}; Set<GeneratedColumn> get $primaryKey => {payload};
@override @override
NoIdRow map(Map<String, dynamic> data, {String? tablePrefix}) { NoIdRow map(Map<String, dynamic> data, {String? tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';
@ -89,6 +91,8 @@ class $NoIdsTable extends Table with TableInfo<$NoIdsTable, NoIdRow> {
@override @override
bool get withoutRowId => true; bool get withoutRowId => true;
@override
bool get dontWriteConstraints => true;
} }
class WithDefault extends DataClass implements Insertable<WithDefault> { class WithDefault extends DataClass implements Insertable<WithDefault> {
@ -219,11 +223,15 @@ class $WithDefaultsTable extends Table
final VerificationMeta _aMeta = const VerificationMeta('a'); final VerificationMeta _aMeta = const VerificationMeta('a');
late final GeneratedColumn<String> a = GeneratedColumn<String>( late final GeneratedColumn<String> a = GeneratedColumn<String>(
'a', aliasedName, true, 'a', aliasedName, true,
type: DriftSqlType.string, requiredDuringInsert: false); type: DriftSqlType.string,
requiredDuringInsert: false,
defaultValue: const CustomExpression('\'something\''));
final VerificationMeta _bMeta = const VerificationMeta('b'); final VerificationMeta _bMeta = const VerificationMeta('b');
late final GeneratedColumn<int> b = GeneratedColumn<int>( late final GeneratedColumn<int> b = GeneratedColumn<int>(
'b', aliasedName, true, 'b', aliasedName, true,
type: DriftSqlType.int, requiredDuringInsert: false); type: DriftSqlType.int,
requiredDuringInsert: false,
defaultConstraints: 'UNIQUE');
@override @override
List<GeneratedColumn> get $columns => [a, b]; List<GeneratedColumn> get $columns => [a, b];
@override @override
@ -261,6 +269,9 @@ class $WithDefaultsTable extends Table
$WithDefaultsTable createAlias(String alias) { $WithDefaultsTable createAlias(String alias) {
return $WithDefaultsTable(attachedDatabase, alias); return $WithDefaultsTable(attachedDatabase, alias);
} }
@override
bool get dontWriteConstraints => true;
} }
class WithConstraint extends DataClass implements Insertable<WithConstraint> { class WithConstraint extends DataClass implements Insertable<WithConstraint> {
@ -466,6 +477,9 @@ class $WithConstraintsTable extends Table
$WithConstraintsTable createAlias(String alias) { $WithConstraintsTable createAlias(String alias) {
return $WithConstraintsTable(attachedDatabase, alias); return $WithConstraintsTable(attachedDatabase, alias);
} }
@override
bool get dontWriteConstraints => true;
} }
class Config extends DataClass implements Insertable<Config> { class Config extends DataClass implements Insertable<Config> {
@ -486,11 +500,11 @@ class Config extends DataClass implements Insertable<Config> {
map['config_value'] = Variable<String>(configValue); map['config_value'] = Variable<String>(configValue);
} }
if (!nullToAbsent || syncState != null) { if (!nullToAbsent || syncState != null) {
final converter = $ConfigTable.$convertersyncState; final converter = $ConfigTable.$convertersyncStaten;
map['sync_state'] = Variable<int>(converter.toSql(syncState)); map['sync_state'] = Variable<int>(converter.toSql(syncState));
} }
if (!nullToAbsent || syncStateImplicit != null) { if (!nullToAbsent || syncStateImplicit != null) {
final converter = $ConfigTable.$convertersyncStateImplicit; final converter = $ConfigTable.$convertersyncStateImplicitn;
map['sync_state_implicit'] = map['sync_state_implicit'] =
Variable<int>(converter.toSql(syncStateImplicit)); Variable<int>(converter.toSql(syncStateImplicit));
} }
@ -629,11 +643,11 @@ class ConfigCompanion extends UpdateCompanion<Config> {
map['config_value'] = Variable<String>(configValue.value); map['config_value'] = Variable<String>(configValue.value);
} }
if (syncState.present) { if (syncState.present) {
final converter = $ConfigTable.$convertersyncState; final converter = $ConfigTable.$convertersyncStaten;
map['sync_state'] = Variable<int>(converter.toSql(syncState.value)); map['sync_state'] = Variable<int>(converter.toSql(syncState.value));
} }
if (syncStateImplicit.present) { if (syncStateImplicit.present) {
final converter = $ConfigTable.$convertersyncStateImplicit; final converter = $ConfigTable.$convertersyncStateImplicitn;
map['sync_state_implicit'] = map['sync_state_implicit'] =
Variable<int>(converter.toSql(syncStateImplicit.value)); Variable<int>(converter.toSql(syncStateImplicit.value));
} }
@ -660,7 +674,9 @@ class $ConfigTable extends Table with TableInfo<$ConfigTable, Config> {
final VerificationMeta _configKeyMeta = const VerificationMeta('configKey'); final VerificationMeta _configKeyMeta = const VerificationMeta('configKey');
late final GeneratedColumn<String> configKey = GeneratedColumn<String>( late final GeneratedColumn<String> configKey = GeneratedColumn<String>(
'config_key', aliasedName, false, 'config_key', aliasedName, false,
type: DriftSqlType.string, requiredDuringInsert: true); type: DriftSqlType.string,
requiredDuringInsert: true,
defaultConstraints: 'PRIMARY KEY');
final VerificationMeta _configValueMeta = final VerificationMeta _configValueMeta =
const VerificationMeta('configValue'); const VerificationMeta('configValue');
late final GeneratedColumn<String> configValue = GeneratedColumn<String>( late final GeneratedColumn<String> configValue = GeneratedColumn<String>(
@ -670,14 +686,14 @@ class $ConfigTable extends Table with TableInfo<$ConfigTable, Config> {
late final GeneratedColumnWithTypeConverter<SyncType?, int> syncState = late final GeneratedColumnWithTypeConverter<SyncType?, int> syncState =
GeneratedColumn<int>('sync_state', aliasedName, true, GeneratedColumn<int>('sync_state', aliasedName, true,
type: DriftSqlType.int, requiredDuringInsert: false) type: DriftSqlType.int, requiredDuringInsert: false)
.withConverter<SyncType?>($ConfigTable.$convertersyncState); .withConverter<SyncType?>($ConfigTable.$convertersyncStaten);
final VerificationMeta _syncStateImplicitMeta = final VerificationMeta _syncStateImplicitMeta =
const VerificationMeta('syncStateImplicit'); const VerificationMeta('syncStateImplicit');
late final GeneratedColumnWithTypeConverter<SyncType?, int> late final GeneratedColumnWithTypeConverter<SyncType?, int>
syncStateImplicit = GeneratedColumn<int>( syncStateImplicit = GeneratedColumn<int>(
'sync_state_implicit', aliasedName, true, 'sync_state_implicit', aliasedName, true,
type: DriftSqlType.int, requiredDuringInsert: false) type: DriftSqlType.int, requiredDuringInsert: false)
.withConverter<SyncType?>($ConfigTable.$convertersyncStateImplicit); .withConverter<SyncType?>($ConfigTable.$convertersyncStateImplicitn);
@override @override
List<GeneratedColumn> get $columns => List<GeneratedColumn> get $columns =>
[configKey, configValue, syncState, syncStateImplicit]; [configKey, configValue, syncState, syncStateImplicit];
@ -708,7 +724,7 @@ class $ConfigTable extends Table with TableInfo<$ConfigTable, Config> {
} }
@override @override
Set<GeneratedColumn> get $primaryKey => const <GeneratedColumn>{}; Set<GeneratedColumn> get $primaryKey => {configKey};
@override @override
Config map(Map<String, dynamic> data, {String? tablePrefix}) { Config map(Map<String, dynamic> data, {String? tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';
@ -717,10 +733,10 @@ class $ConfigTable extends Table with TableInfo<$ConfigTable, Config> {
.read(DriftSqlType.string, data['${effectivePrefix}config_key'])!, .read(DriftSqlType.string, data['${effectivePrefix}config_key'])!,
configValue: attachedDatabase.options.types configValue: attachedDatabase.options.types
.read(DriftSqlType.string, data['${effectivePrefix}config_value']), .read(DriftSqlType.string, data['${effectivePrefix}config_value']),
syncState: $ConfigTable.$convertersyncState.fromSql(attachedDatabase syncState: $ConfigTable.$convertersyncStaten.fromSql(attachedDatabase
.options.types .options.types
.read(DriftSqlType.int, data['${effectivePrefix}sync_state'])), .read(DriftSqlType.int, data['${effectivePrefix}sync_state'])),
syncStateImplicit: $ConfigTable.$convertersyncStateImplicit.fromSql( syncStateImplicit: $ConfigTable.$convertersyncStateImplicitn.fromSql(
attachedDatabase.options.types.read( attachedDatabase.options.types.read(
DriftSqlType.int, data['${effectivePrefix}sync_state_implicit'])), DriftSqlType.int, data['${effectivePrefix}sync_state_implicit'])),
); );
@ -733,14 +749,16 @@ class $ConfigTable extends Table with TableInfo<$ConfigTable, Config> {
static TypeConverter<SyncType, int> $convertersyncState = static TypeConverter<SyncType, int> $convertersyncState =
const SyncTypeConverter(); const SyncTypeConverter();
static TypeConverter<SyncType?, int> $convertersyncStaten = static TypeConverter<SyncType?, int?> $convertersyncStaten =
NullAwareTypeConverter.wrap($convertersyncState); NullAwareTypeConverter.wrap($convertersyncState);
static TypeConverter<SyncType, int> $convertersyncStateImplicit = static TypeConverter<SyncType, int> $convertersyncStateImplicit =
const EnumIndexConverter<SyncType>(SyncType.values); const EnumIndexConverter<SyncType>(SyncType.values);
static TypeConverter<SyncType?, int> $convertersyncStateImplicitn = static TypeConverter<SyncType?, int?> $convertersyncStateImplicitn =
NullAwareTypeConverter.wrap($convertersyncStateImplicit); NullAwareTypeConverter.wrap($convertersyncStateImplicit);
@override @override
bool get isStrict => true; bool get isStrict => true;
@override
bool get dontWriteConstraints => true;
} }
class MytableData extends DataClass implements Insertable<MytableData> { class MytableData extends DataClass implements Insertable<MytableData> {
@ -994,6 +1012,9 @@ class $MytableTable extends Table with TableInfo<$MytableTable, MytableData> {
$MytableTable createAlias(String alias) { $MytableTable createAlias(String alias) {
return $MytableTable(attachedDatabase, alias); return $MytableTable(attachedDatabase, alias);
} }
@override
bool get dontWriteConstraints => true;
} }
class EMail extends DataClass implements Insertable<EMail> { class EMail extends DataClass implements Insertable<EMail> {
@ -1200,6 +1221,8 @@ class $EmailTable extends Table
return $EmailTable(attachedDatabase, alias); return $EmailTable(attachedDatabase, alias);
} }
@override
bool get dontWriteConstraints => true;
@override @override
String get moduleAndArgs => 'fts5(sender, title, body)'; String get moduleAndArgs => 'fts5(sender, title, body)';
} }
@ -1377,6 +1400,9 @@ class $WeirdTableTable extends Table
$WeirdTableTable createAlias(String alias) { $WeirdTableTable createAlias(String alias) {
return $WeirdTableTable(attachedDatabase, alias); return $WeirdTableTable(attachedDatabase, alias);
} }
@override
bool get dontWriteConstraints => true;
} }
class MyViewData extends DataClass { class MyViewData extends DataClass {
@ -1478,10 +1504,10 @@ class MyView extends ViewInfo<MyView, MyViewData> implements HasResultSet {
.read(DriftSqlType.string, data['${effectivePrefix}config_key'])!, .read(DriftSqlType.string, data['${effectivePrefix}config_key'])!,
configValue: attachedDatabase.options.types configValue: attachedDatabase.options.types
.read(DriftSqlType.string, data['${effectivePrefix}config_value']), .read(DriftSqlType.string, data['${effectivePrefix}config_value']),
syncState: MyView.$convertersyncState.fromSql(attachedDatabase syncState: $ConfigTable.$convertersyncStaten.fromSql(attachedDatabase
.options.types .options.types
.read(DriftSqlType.int, data['${effectivePrefix}sync_state'])), .read(DriftSqlType.int, data['${effectivePrefix}sync_state'])),
syncStateImplicit: MyView.$convertersyncStateImplicit.fromSql( syncStateImplicit: $ConfigTable.$convertersyncStateImplicitn.fromSql(
attachedDatabase.options.types.read( attachedDatabase.options.types.read(
DriftSqlType.int, data['${effectivePrefix}sync_state_implicit'])), DriftSqlType.int, data['${effectivePrefix}sync_state_implicit'])),
); );
@ -1496,12 +1522,12 @@ class MyView extends ViewInfo<MyView, MyViewData> implements HasResultSet {
late final GeneratedColumnWithTypeConverter<SyncType?, int> syncState = late final GeneratedColumnWithTypeConverter<SyncType?, int> syncState =
GeneratedColumn<int>('sync_state', aliasedName, true, GeneratedColumn<int>('sync_state', aliasedName, true,
type: DriftSqlType.int) type: DriftSqlType.int)
.withConverter<SyncType?>(MyView.$convertersyncState); .withConverter<SyncType?>($ConfigTable.$convertersyncStaten);
late final GeneratedColumnWithTypeConverter<SyncType?, int> late final GeneratedColumnWithTypeConverter<SyncType?, int>
syncStateImplicit = GeneratedColumn<int>( syncStateImplicit = GeneratedColumn<int>(
'sync_state_implicit', aliasedName, true, 'sync_state_implicit', aliasedName, true,
type: DriftSqlType.int) type: DriftSqlType.int)
.withConverter<SyncType?>(MyView.$convertersyncStateImplicit); .withConverter<SyncType?>($ConfigTable.$convertersyncStateImplicitn);
@override @override
MyView createAlias(String alias) { MyView createAlias(String alias) {
return MyView(attachedDatabase, alias); return MyView(attachedDatabase, alias);
@ -1534,8 +1560,7 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
return customInsert( return customInsert(
'REPLACE INTO config (config_key, config_value) VALUES (?1, ?2)', 'REPLACE INTO config (config_key, config_value) VALUES (?1, ?2)',
variables: [Variable<String>(key), Variable<String>(value)], variables: [Variable<String>(key), Variable<String>(value)],
updates: {}, updates: {config},
updateKind: UpdateKind.delete,
); );
} }
@ -1605,11 +1630,11 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
'SELECT config_key FROM config WHERE ${generatedpred.sql} AND(sync_state = ?1 OR sync_state_implicit IN ($expandedvar2))', 'SELECT config_key FROM config WHERE ${generatedpred.sql} AND(sync_state = ?1 OR sync_state_implicit IN ($expandedvar2))',
variables: [ variables: [
Variable<int>(NullAwareTypeConverter.wrapToSql( Variable<int>(NullAwareTypeConverter.wrapToSql(
$ConfigTable.$convertersyncStaten, var1)), $ConfigTable.$convertersyncState, var1)),
...generatedpred.introducedVariables, ...generatedpred.introducedVariables,
for (var $ in var2) for (var $ in var2)
Variable<int>(NullAwareTypeConverter.wrapToSql( Variable<int>(NullAwareTypeConverter.wrapToSql(
$ConfigTable.$convertersyncStateImplicitn, $)) $ConfigTable.$convertersyncStateImplicit, $))
], ],
readsFrom: { readsFrom: {
config, config,
@ -1703,35 +1728,24 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
configKey: row.read<String>('config_key'), configKey: row.read<String>('config_key'),
configValue: row.readNullable<String>('config_value'), configValue: row.readNullable<String>('config_value'),
syncState: NullAwareTypeConverter.wrapFromSql( syncState: NullAwareTypeConverter.wrapFromSql(
$ConfigTable.$convertersyncStaten, $ConfigTable.$convertersyncState,
row.readNullable<int>('sync_state')), row.readNullable<int>('sync_state')),
syncStateImplicit: NullAwareTypeConverter.wrapFromSql( syncStateImplicit: NullAwareTypeConverter.wrapFromSql(
$ConfigTable.$convertersyncStateImplicitn, $ConfigTable.$convertersyncStateImplicit,
row.readNullable<int>('sync_state_implicit')), row.readNullable<int>('sync_state_implicit')),
); );
}); });
} }
Selectable<ReadViewResult> readView() { Selectable<MyViewData> readView() {
return customSelect('SELECT * FROM my_view', variables: [], readsFrom: { return customSelect('SELECT * FROM my_view', variables: [], readsFrom: {
config, config,
}).map((QueryRow row) { }).asyncMap(myView.mapFromRow);
return ReadViewResult(
row: row,
configKey: row.read<String>('config_key'),
configValue: row.readNullable<String>('config_value'),
syncState: NullAwareTypeConverter.wrapFromSql(
MyView.$convertersyncStaten, row.readNullable<int>('sync_state')),
syncStateImplicit: NullAwareTypeConverter.wrapFromSql(
MyView.$convertersyncStateImplicitn,
row.readNullable<int>('sync_state_implicit')),
);
});
} }
Selectable<int> cfeTest() { Selectable<int> cfeTest() {
return customSelect( return customSelect(
'WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM cnt LIMIT 1000000) SELECT x FROM cnt', 'WITH RECURSIVE cnt (x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM cnt LIMIT 1000000) SELECT x FROM cnt',
variables: [], variables: [],
readsFrom: {}).map((QueryRow row) => row.read<int>('x')); readsFrom: {}).map((QueryRow row) => row.read<int>('x'));
} }
@ -1797,22 +1811,8 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
weirdTable, weirdTable,
myTrigger, myTrigger,
myView, myView,
null,
null,
null,
null,
null,
null,
OnCreateQuery( OnCreateQuery(
'INSERT INTO config (config_key, config_value) VALUES (\'key\', \'values\')'), 'INSERT INTO config (config_key, config_value) VALUES (\'key\', \'values\')')
null,
null,
null,
null,
null,
null,
null,
null
]; ];
@override @override
DriftDatabaseOptions get options => DriftDatabaseOptions get options =>
@ -1949,44 +1949,9 @@ class ReadRowIdResult extends CustomResultSet {
typedef ReadRowId$expr = Expression<int> Function($ConfigTable config); typedef ReadRowId$expr = Expression<int> 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,
this.configValue,
this.syncState,
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 { class NestedResult extends CustomResultSet {
final WithDefault defaults; final WithDefault defaults;
finalList<WithConstraint> nestedQuery0; final List<WithConstraint> nestedQuery0;
NestedResult({ NestedResult({
required QueryRow row, required QueryRow row,
required this.defaults, required this.defaults,

View File

@ -325,7 +325,7 @@ class Category extends DataClass implements Insertable<Category> {
map['id'] = Variable<int>(id); map['id'] = Variable<int>(id);
map['desc'] = Variable<String>(description); map['desc'] = Variable<String>(description);
{ {
final converter = $CategoriesTable.$converterpriorityn; final converter = $CategoriesTable.$converterpriority;
map['priority'] = Variable<int>(converter.toSql(priority)); map['priority'] = Variable<int>(converter.toSql(priority));
} }
return map; return map;
@ -450,7 +450,7 @@ class CategoriesCompanion extends UpdateCompanion<Category> {
map['desc'] = Variable<String>(description.value); map['desc'] = Variable<String>(description.value);
} }
if (priority.present) { if (priority.present) {
final converter = $CategoriesTable.$converterpriorityn; final converter = $CategoriesTable.$converterpriority;
map['priority'] = Variable<int>(converter.toSql(priority.value)); map['priority'] = Variable<int>(converter.toSql(priority.value));
} }
return map; return map;
@ -495,8 +495,7 @@ class $CategoriesTable extends Categories
type: DriftSqlType.int, type: DriftSqlType.int,
requiredDuringInsert: false, requiredDuringInsert: false,
defaultValue: const Constant(0)) defaultValue: const Constant(0))
.withConverter<CategoryPriority>( .withConverter<CategoryPriority>($CategoriesTable.$converterpriority);
$CategoriesTable.$converterpriorityn);
final VerificationMeta _descriptionInUpperCaseMeta = final VerificationMeta _descriptionInUpperCaseMeta =
const VerificationMeta('descriptionInUpperCase'); const VerificationMeta('descriptionInUpperCase');
@override @override
@ -546,7 +545,7 @@ class $CategoriesTable extends Categories
.read(DriftSqlType.int, data['${effectivePrefix}id'])!, .read(DriftSqlType.int, data['${effectivePrefix}id'])!,
description: attachedDatabase.options.types description: attachedDatabase.options.types
.read(DriftSqlType.string, data['${effectivePrefix}desc'])!, .read(DriftSqlType.string, data['${effectivePrefix}desc'])!,
priority: $CategoriesTable.$converterpriorityn.fromSql(attachedDatabase priority: $CategoriesTable.$converterpriority.fromSql(attachedDatabase
.options.types .options.types
.read(DriftSqlType.int, data['${effectivePrefix}priority'])!), .read(DriftSqlType.int, data['${effectivePrefix}priority'])!),
descriptionInUpperCase: attachedDatabase.options.types.read( descriptionInUpperCase: attachedDatabase.options.types.read(
@ -1095,7 +1094,7 @@ class TableWithoutPKCompanion extends UpdateCompanion<CustomRowClass> {
map['web_safe_int'] = Variable<BigInt>(webSafeInt.value); map['web_safe_int'] = Variable<BigInt>(webSafeInt.value);
} }
if (custom.present) { if (custom.present) {
final converter = $TableWithoutPKTable.$convertercustomn; final converter = $TableWithoutPKTable.$convertercustom;
map['custom'] = Variable<String>(converter.toSql(custom.value)); map['custom'] = Variable<String>(converter.toSql(custom.value));
} }
return map; return map;
@ -1121,6 +1120,8 @@ class _$CustomRowClassInsertable implements Insertable<CustomRowClass> {
@override @override
Map<String, Expression> toColumns(bool nullToAbsent) { Map<String, Expression> toColumns(bool nullToAbsent) {
return TableWithoutPKCompanion( return TableWithoutPKCompanion(
notReallyAnId: Value(_object.notReallyAnId),
someFloat: Value(_object.someFloat),
custom: Value(_object.custom), custom: Value(_object.custom),
webSafeInt: Value(_object.webSafeInt), webSafeInt: Value(_object.webSafeInt),
).toColumns(false); ).toColumns(false);
@ -1162,8 +1163,7 @@ class $TableWithoutPKTable extends TableWithoutPK
type: DriftSqlType.string, type: DriftSqlType.string,
requiredDuringInsert: false, requiredDuringInsert: false,
clientDefault: _uuid.v4) clientDefault: _uuid.v4)
.withConverter<MyCustomObject>( .withConverter<MyCustomObject>($TableWithoutPKTable.$convertercustom);
$TableWithoutPKTable.$convertercustomn);
@override @override
List<GeneratedColumn> get $columns => List<GeneratedColumn> get $columns =>
[notReallyAnId, someFloat, webSafeInt, custom]; [notReallyAnId, someFloat, webSafeInt, custom];
@ -1210,7 +1210,7 @@ class $TableWithoutPKTable extends TableWithoutPK
.read(DriftSqlType.int, data['${effectivePrefix}not_really_an_id'])!, .read(DriftSqlType.int, data['${effectivePrefix}not_really_an_id'])!,
attachedDatabase.options.types attachedDatabase.options.types
.read(DriftSqlType.double, data['${effectivePrefix}some_float'])!, .read(DriftSqlType.double, data['${effectivePrefix}some_float'])!,
custom: $TableWithoutPKTable.$convertercustomn.fromSql(attachedDatabase custom: $TableWithoutPKTable.$convertercustom.fromSql(attachedDatabase
.options.types .options.types
.read(DriftSqlType.string, data['${effectivePrefix}custom'])!), .read(DriftSqlType.string, data['${effectivePrefix}custom'])!),
webSafeInt: attachedDatabase.options.types webSafeInt: attachedDatabase.options.types
@ -1234,7 +1234,7 @@ class PureDefault extends DataClass implements Insertable<PureDefault> {
Map<String, Expression> toColumns(bool nullToAbsent) { Map<String, Expression> toColumns(bool nullToAbsent) {
final map = <String, Expression>{}; final map = <String, Expression>{};
if (!nullToAbsent || txt != null) { if (!nullToAbsent || txt != null) {
final converter = $PureDefaultsTable.$convertertxt; final converter = $PureDefaultsTable.$convertertxtn;
map['insert'] = Variable<String>(converter.toSql(txt)); map['insert'] = Variable<String>(converter.toSql(txt));
} }
return map; return map;
@ -1250,7 +1250,7 @@ class PureDefault extends DataClass implements Insertable<PureDefault> {
{ValueSerializer? serializer}) { {ValueSerializer? serializer}) {
serializer ??= driftRuntimeOptions.defaultSerializer; serializer ??= driftRuntimeOptions.defaultSerializer;
return PureDefault( return PureDefault(
txt: $PureDefaultsTable.$convertertxt txt: $PureDefaultsTable.$convertertxtn
.fromJson(serializer.fromJson<Map<dynamic, dynamic>>(json['txt'])), .fromJson(serializer.fromJson<Map<dynamic, dynamic>>(json['txt'])),
); );
} }
@ -1264,7 +1264,7 @@ class PureDefault extends DataClass implements Insertable<PureDefault> {
serializer ??= driftRuntimeOptions.defaultSerializer; serializer ??= driftRuntimeOptions.defaultSerializer;
return <String, dynamic>{ return <String, dynamic>{
'txt': serializer.toJson<Map<dynamic, dynamic>?>( 'txt': serializer.toJson<Map<dynamic, dynamic>?>(
$PureDefaultsTable.$convertertxt.toJson(txt)), $PureDefaultsTable.$convertertxtn.toJson(txt)),
}; };
} }
@ -1313,7 +1313,7 @@ class PureDefaultsCompanion extends UpdateCompanion<PureDefault> {
Map<String, Expression> toColumns(bool nullToAbsent) { Map<String, Expression> toColumns(bool nullToAbsent) {
final map = <String, Expression>{}; final map = <String, Expression>{};
if (txt.present) { if (txt.present) {
final converter = $PureDefaultsTable.$convertertxt; final converter = $PureDefaultsTable.$convertertxtn;
map['insert'] = Variable<String>(converter.toSql(txt.value)); map['insert'] = Variable<String>(converter.toSql(txt.value));
} }
return map; return map;
@ -1339,7 +1339,7 @@ class $PureDefaultsTable extends PureDefaults
late final GeneratedColumnWithTypeConverter<MyCustomObject?, String> txt = late final GeneratedColumnWithTypeConverter<MyCustomObject?, String> txt =
GeneratedColumn<String>('insert', aliasedName, true, GeneratedColumn<String>('insert', aliasedName, true,
type: DriftSqlType.string, requiredDuringInsert: false) type: DriftSqlType.string, requiredDuringInsert: false)
.withConverter<MyCustomObject?>($PureDefaultsTable.$convertertxt); .withConverter<MyCustomObject?>($PureDefaultsTable.$convertertxtn);
@override @override
List<GeneratedColumn> get $columns => [txt]; List<GeneratedColumn> get $columns => [txt];
@override @override
@ -1361,7 +1361,7 @@ class $PureDefaultsTable extends PureDefaults
PureDefault map(Map<String, dynamic> data, {String? tablePrefix}) { PureDefault map(Map<String, dynamic> data, {String? tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';
return PureDefault( return PureDefault(
txt: $PureDefaultsTable.$convertertxt.fromSql(attachedDatabase txt: $PureDefaultsTable.$convertertxtn.fromSql(attachedDatabase
.options.types .options.types
.read(DriftSqlType.string, data['${effectivePrefix}insert'])), .read(DriftSqlType.string, data['${effectivePrefix}insert'])),
); );
@ -1372,10 +1372,10 @@ class $PureDefaultsTable extends PureDefaults
return $PureDefaultsTable(attachedDatabase, alias); return $PureDefaultsTable(attachedDatabase, alias);
} }
static JsonTypeConverter<MyCustomObject, String> $convertertxt = static JsonTypeConverter2<MyCustomObject, String, Map<dynamic, dynamic>>
const CustomJsonConverter(); $convertertxt = const CustomJsonConverter();
static JsonTypeConverter<MyCustomObject?, String> $convertertxtn = static JsonTypeConverter2<MyCustomObject?, String?, Map<dynamic, dynamic>?>
JsonTypeConverter2.asNullable($convertertxt); $convertertxtn = JsonTypeConverter2.asNullable($convertertxt);
} }
class CategoryTodoCountViewData extends DataClass { class CategoryTodoCountViewData extends DataClass {
@ -1664,7 +1664,7 @@ abstract class _$TodoDb extends GeneratedDatabase {
variables: [], variables: [],
readsFrom: { readsFrom: {
tableWithoutPK, tableWithoutPK,
}).map((QueryRow row) => $TableWithoutPKTable.$convertercustomn }).map((QueryRow row) => $TableWithoutPKTable.$convertercustom
.fromSql(row.read<String>('custom'))); .fromSql(row.read<String>('custom')));
} }
@ -1741,6 +1741,7 @@ mixin _$SomeDaoMixin on DatabaseAccessor<TodoDb> {
$TodosTableTable get todosTable => attachedDatabase.todosTable; $TodosTableTable get todosTable => attachedDatabase.todosTable;
$TodoWithCategoryViewView get todoWithCategoryView => $TodoWithCategoryViewView get todoWithCategoryView =>
attachedDatabase.todoWithCategoryView; attachedDatabase.todoWithCategoryView;
$CategoriesTable get categories => attachedDatabase.categories;
Selectable<TodoEntry> todosForUser({required int user}) { Selectable<TodoEntry> todosForUser({required int user}) {
return customSelect( 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', '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',

View File

@ -324,6 +324,7 @@ class DriftTableResolver extends LocalElementResolver<DiscoveredDriftTable> {
strict: table.isStrict, strict: table.isStrict,
tableConstraints: tableConstraints, tableConstraints: tableConstraints,
virtualTableData: virtualTableData, virtualTableData: virtualTableData,
writeDefaultConstraints: false,
); );
} }

View File

@ -42,6 +42,7 @@ class DriftViewResolver extends DriftElementResolver<DiscoveredDriftView> {
declaration: DriftDeclaration.driftFile(stmt, file.ownUri), declaration: DriftDeclaration.driftFile(stmt, file.ownUri),
nullable: type?.nullable == true, nullable: type?.nullable == true,
typeConverter: converter, typeConverter: converter,
foreignConverter: true,
); );
columns.add(driftColumn); columns.add(driftColumn);

View File

@ -156,7 +156,7 @@ class ElementSerializer {
'nameInDart': column.nameInDart, 'nameInDart': column.nameInDart,
'declaration': column.declaration.toJson(), 'declaration': column.declaration.toJson(),
'typeConverter': column.typeConverter != null 'typeConverter': column.typeConverter != null
? _serializeTypeConverter(column.typeConverter!) ? _serializeTypeConverter(column, column.typeConverter!)
: null, : null,
'clientDefaultCode': column.clientDefaultCode?.toJson(), 'clientDefaultCode': column.clientDefaultCode?.toJson(),
'defaultArgument': column.defaultArgument?.toJson(), 'defaultArgument': column.defaultArgument?.toJson(),
@ -254,7 +254,8 @@ class ElementSerializer {
return action?.name; return action?.name;
} }
Map<String, Object?> _serializeTypeConverter(AppliedTypeConverter converter) { Map<String, Object?> _serializeTypeConverter(
DriftColumn appliedTo, AppliedTypeConverter converter) {
return { return {
'expression': converter.expression.toJson(), 'expression': converter.expression.toJson(),
'dart_type': converter.dartType.accept(const _DartTypeSerializer()), 'dart_type': converter.dartType.accept(const _DartTypeSerializer()),
@ -262,6 +263,8 @@ class ElementSerializer {
'sql_type': converter.sqlType.name, 'sql_type': converter.sqlType.name,
'dart_type_is_nullable': converter.dartTypeIsNullable, 'dart_type_is_nullable': converter.dartTypeIsNullable,
'sql_type_is_nullable': converter.sqlTypeIsNullable, 'sql_type_is_nullable': converter.sqlTypeIsNullable,
if (converter.owningColumn != appliedTo)
'owner': _serializeColumnReference(converter.owningColumn),
}; };
} }
@ -345,6 +348,7 @@ class _DartTypeSerializer extends TypeVisitor<Map<String, Object?>> {
class ElementDeserializer { class ElementDeserializer {
final Map<Uri, LibraryElement> _loadedLibraries = {}; final Map<Uri, LibraryElement> _loadedLibraries = {};
final List<DriftElementId> _currentlyReading = [];
final DriftAnalysisDriver driver; final DriftAnalysisDriver driver;
@ -400,15 +404,23 @@ class ElementDeserializer {
'Analysis data for ${id..libraryUri} not found'); 'Analysis data for ${id..libraryUri} not found');
} }
assert(!_currentlyReading.contains(id));
try { try {
_currentlyReading.add(id);
final result = await _readDriftElement(data[id.name] as Map); final result = await _readDriftElement(data[id.name] as Map);
state state
..result = result ..result = result
..isUpToDate = true; ..isUpToDate = true;
return result; return result;
} catch (e, s) { } catch (e, s) {
if (e is CouldNotDeserializeException) rethrow;
throw CouldNotDeserializeException( throw CouldNotDeserializeException(
'Internal error while deserializing $id: $e at \n$s'); 'Internal error while deserializing $id: $e at \n$s');
} finally {
final lastId = _currentlyReading.removeLast();
assert(lastId == id);
} }
} }
@ -460,8 +472,8 @@ class ElementDeserializer {
} }
virtualTableData = VirtualTableData( virtualTableData = VirtualTableData(
json['module'] as String, data['module'] as String,
(json['arguments'] as List).cast(), (data['arguments'] as List).cast(),
recognizedModule, recognizedModule,
); );
} }
@ -635,15 +647,17 @@ class ElementDeserializer {
} }
Future<DriftColumn> _readColumn(Map json) async { Future<DriftColumn> _readColumn(Map json) async {
final rawConverter = json['typeConverter'] as Map?;
return DriftColumn( return DriftColumn(
sqlType: DriftSqlType.values.byName(json['sqlType'] as String), sqlType: DriftSqlType.values.byName(json['sqlType'] as String),
nullable: json['nullable'] as bool, nullable: json['nullable'] as bool,
nameInSql: json['nameInSql'] as String, nameInSql: json['nameInSql'] as String,
nameInDart: json['nameInDart'] as String, nameInDart: json['nameInDart'] as String,
declaration: DriftDeclaration.fromJson(json['declaration'] as Map), declaration: DriftDeclaration.fromJson(json['declaration'] as Map),
typeConverter: json['typeConverter'] != null typeConverter:
? await _readTypeConverter(json['typeConverter'] as Map) rawConverter != null ? await _readTypeConverter(rawConverter) : null,
: null, foreignConverter: rawConverter != null && rawConverter['owner'] != null,
clientDefaultCode: json['clientDefaultCode'] != null clientDefaultCode: json['clientDefaultCode'] != null
? AnnotatedDartCode.fromJson(json['clientDefaultCode'] as Map) ? AnnotatedDartCode.fromJson(json['clientDefaultCode'] as Map)
: null, : null,
@ -661,7 +675,13 @@ class ElementDeserializer {
} }
Future<AppliedTypeConverter> _readTypeConverter(Map json) async { Future<AppliedTypeConverter> _readTypeConverter(Map json) async {
return AppliedTypeConverter( final owner = json['owner'];
DriftColumn? readOwner;
if (owner != null) {
readOwner = await _readDriftColumnReference(owner as Map);
}
final converter = AppliedTypeConverter(
expression: AnnotatedDartCode.fromJson(json['expression'] as Map), expression: AnnotatedDartCode.fromJson(json['expression'] as Map),
dartType: await _readDartType(json['dart_type'] as Map), dartType: await _readDartType(json['dart_type'] as Map),
jsonType: json['json_type'] != null jsonType: json['json_type'] != null
@ -671,6 +691,10 @@ class ElementDeserializer {
dartTypeIsNullable: json['dart_type_is_nullable'] as bool, dartTypeIsNullable: json['dart_type_is_nullable'] as bool,
sqlTypeIsNullable: json['sql_type_is_nullable'] as bool, sqlTypeIsNullable: json['sql_type_is_nullable'] as bool,
); );
if (readOwner != null) converter.owningColumn = readOwner;
return converter;
} }
ReferenceAction? _readAction(String? value) { ReferenceAction? _readAction(String? value) {

View File

@ -142,16 +142,19 @@ class DatabaseWriter {
..write('=> ['); ..write('=> [');
schemaScope schemaScope
..write(elements.map((e) { ..write(elements
if (e is DefinedSqlQuery && e.mode == QueryMode.atCreate) { .map((e) {
final resolved = input.importedQueries[e]!; if (e is DefinedSqlQuery && e.mode == QueryMode.atCreate) {
final sql = schemaScope.sqlCode(resolved.root!); final resolved = input.importedQueries[e]!;
final sql = schemaScope.sqlCode(resolved.root!);
return 'OnCreateQuery(${asDartLiteral(sql)})'; return 'OnCreateQuery(${asDartLiteral(sql)})';
} }
return entityGetters[e]; return entityGetters[e];
}).join(', ')) })
.whereType<String>()
.join(', '))
// close list literal and allSchemaEntities getter // close list literal and allSchemaEntities getter
..write('];\n'); ..write('];\n');

View File

@ -59,7 +59,7 @@ class ResultSetWriter {
} }
into into
..write(modifier) ..write('$modifier ')
..writeDart(nested.resultRowType(scope)) ..writeDart(nested.resultRowType(scope))
..writeln('$fieldName;'); ..writeln('$fieldName;');

View File

@ -131,7 +131,9 @@ class DataClassWriter {
final typeConverter = column.typeConverter; final typeConverter = column.typeConverter;
if (typeConverter != null && typeConverter.alsoAppliesToJsonConversion) { if (typeConverter != null && typeConverter.alsoAppliesToJsonConversion) {
final type = typeConverter.jsonType; final type =
_emitter.dartCode(AnnotatedDartCode.type(typeConverter.jsonType!));
final fromConverter = "serializer.fromJson<$type>(json['$jsonKey'])"; final fromConverter = "serializer.fromJson<$type>(json['$jsonKey'])";
final converterField = _converter(column); final converterField = _converter(column);
deserialized = '$converterField.fromJson($fromConverter)'; deserialized = '$converterField.fromJson($fromConverter)';

View File

@ -239,10 +239,10 @@ class UpdateCompanionWriter {
'Map<String, Expression> toColumns(bool nullToAbsent) {\n' 'Map<String, Expression> toColumns(bool nullToAbsent) {\n'
'return $_companionClass(\n'); 'return $_companionClass(\n');
final fields = info.positionalColumns.followedBy(info.namedColumns.keys); final columns = info.positionalColumns.followedBy(info.namedColumns.values);
for (final field in fields) { for (final columnName in columns) {
final column = final column =
table.columns.firstWhereOrNull((e) => e.nameInDart == field); table.columns.firstWhereOrNull((e) => e.nameInSql == columnName);
if (column != null && !column.isGenerated) { if (column != null && !column.isGenerated) {
final dartName = column.nameInDart; final dartName = column.nameInDart;

View File

@ -69,8 +69,8 @@ abstract class _NodeOrWriter {
AnnotatedDartCode readConverter(AppliedTypeConverter converter, AnnotatedDartCode readConverter(AppliedTypeConverter converter,
{bool forNullable = false}) { {bool forNullable = false}) {
final fieldName = final fieldName =
forNullable ? converter.fieldName : converter.nullableFieldName; forNullable ? converter.nullableFieldName : converter.fieldName;
final table = converter.owningColumn.owner as DriftElementWithResultSet; final table = converter.owningColumn.owner;
return AnnotatedDartCode([ return AnnotatedDartCode([
DartTopLevelSymbol(table.entityInfoName, table.id.libraryUri), DartTopLevelSymbol(table.entityInfoName, table.id.libraryUri),
@ -81,21 +81,31 @@ abstract class _NodeOrWriter {
/// A suitable typename to store an instance of the type converter used here. /// A suitable typename to store an instance of the type converter used here.
AnnotatedDartCode converterType(AppliedTypeConverter converter, AnnotatedDartCode converterType(AppliedTypeConverter converter,
{bool makeNullable = false}) { {bool makeNullable = false}) {
var sqlDartType = dartTypeNames[converter.sqlType]!;
final className = converter.alsoAppliesToJsonConversion
? 'JsonTypeConverter'
: 'TypeConverter';
// Write something like `TypeConverter<MyFancyObject, String>` // Write something like `TypeConverter<MyFancyObject, String>`
return AnnotatedDartCode([ return AnnotatedDartCode.build((b) {
DartTopLevelSymbol.drift(className), var sqlDartType = dartTypeNames[converter.sqlType]!;
'<', final className = converter.alsoAppliesToJsonConversion
...AnnotatedDartCode.type(converter.dartType).elements, ? 'JsonTypeConverter2'
if (makeNullable) '?', : 'TypeConverter';
',',
sqlDartType, b
'>', ..addSymbol(className, AnnotatedDartCode.drift)
]); ..addText('<')
..addDartType(converter.dartType)
..questionMarkIfNullable(makeNullable)
..addText(',')
..addTopLevel(sqlDartType)
..questionMarkIfNullable(makeNullable);
if (converter.alsoAppliesToJsonConversion) {
b
..addText(',')
..addDartType(converter.jsonType!)
..questionMarkIfNullable(makeNullable);
}
b.addText('>');
});
} }
AnnotatedDartCode dartType(HasType hasType) { AnnotatedDartCode dartType(HasType hasType) {
@ -306,3 +316,9 @@ String thisIfNeeded(String getter, Set<String> locals) {
return getter; return getter;
} }
extension on AnnotatedDartCodeBuilder {
void questionMarkIfNullable(bool nullable) {
if (nullable) addText('?');
}
}