dsql 0.0.8 copy "dsql: ^0.0.8" to clipboard
dsql: ^0.0.8 copied to clipboard

outdated

Dart SQL library for generating .dart files from .sql files

example/lib/dsql.dart

import 'dart:io';
import 'package:dsql/dsql.dart';

// **************************
// Generated by DSQL don't change by hand!
// **************************

// UserEntity

class UserEntity {
  final String id;
  final String name;
  final String email;
  final String password;
  final String? image;
  final DateTime createdAt;
  final bool enabled;

  const UserEntity({
    required this.id,
    required this.name,
    required this.email,
    required this.password,
    this.image,
    required this.createdAt,
    required this.enabled,
  });

  Map<String, dynamic> toMap() => {
        'id': id,
        'name': name,
        'email': email,
        'password': password,
        'image': image,
        'created_at': createdAt,
        'enabled': enabled,
      };

  static UserEntity fromMap(Map<String, dynamic> map) => UserEntity(
        id: map['id'] as String,
        name: map['name'] as String,
        email: map['email'] as String,
        password: map['password'] as String,
        image: map['image'] as String,
        createdAt: map['created_at'] as DateTime,
        enabled: map['enabled'] as bool,
      );

  static UserEntity fromRow(List row) {
    final [
      String id,
      String name,
      String email,
      String password,
      String? image,
      DateTime createdAt,
      bool enabled
    ] = row;

    return UserEntity(
      id: id,
      name: name,
      email: email,
      password: password,
      image: image,
      createdAt: createdAt,
      enabled: enabled,
    );
  }

  @override
  int get hashCode =>
      id.hashCode ^
      name.hashCode ^
      email.hashCode ^
      password.hashCode ^
      image.hashCode ^
      createdAt.hashCode ^
      enabled.hashCode;

  @override
  bool operator ==(covariant UserEntity other) {
    if (identical(this, other)) return true;
    if (runtimeType != other.runtimeType) return false;
    return id == other.id &&
        name == other.name &&
        email == other.email &&
        password == other.password &&
        image == other.image &&
        createdAt == other.createdAt &&
        enabled == other.enabled;
  }
}

// UserRepository

class UserRepository {
  final PostgreSQLConnection conn;

  UserRepository(this.conn);

  Future<UserEntity> create({
    required String name,
    required String email,
    required String password,
  }) async {
    try {
      final result = await conn.query(
        'INSERT INTO tb_users (name, email, password) VALUES (@name, @email, @password) RETURNING *',
        substitutionValues: {
          'name': name,
          'email': email,
          'password': password,
        },
      );

      return UserEntity.fromRow(result.first);
    } on PostgreSQLException catch (e) {
      throw Exception(e.message);
    } on Exception catch (e) {
      throw Exception(e);
    }
  }

  Future<List<UserEntity>> findMany({
    StringFilter? id,
    StringFilter? name,
    StringFilter? email,
    StringFilter? password,
    StringFilter? image,
    TimestampFilter? createdAt,
    BooleanFilter? enabled,
  }) async {
    try {
      PostgreSQLResult result;

      final filters = <String, Filter>{
        if (id != null) 'id': id,
        if (name != null) 'name': name,
        if (email != null) 'email': email,
        if (password != null) 'password': password,
        if (image != null) 'image': image,
        if (createdAt != null) 'createdAt': createdAt,
        if (enabled != null) 'enabled': enabled,
      };

      if (filters.isNotEmpty) {
        result = await conn.query(
          'SELECT * FROM tb_users WHERE ${filters.entries.map((e) => '${DSQLUtils.toSnakeCase(e.key)} ${e.value.operator} @${e.key}').join(' OR ')};',
          substitutionValues: {
            ...filters.map((k, v) => MapEntry(k, v.value)),
          },
        );
      } else {
        result = await conn.query(
          'SELECT * FROM tb_users;',
        );
      }

      return result.map(UserEntity.fromRow).toList();
    } on PostgreSQLException catch (e) {
      throw Exception(e.message);
    } on Exception catch (e) {
      throw Exception(e);
    }
  }

  Future<UserEntity?> findOne(String id) async {
    try {
      final result = await conn.query(
        'SELECT * FROM tb_users WHERE id = @id;',
        substitutionValues: {
          'id': id,
        },
      );

      return result.isNotEmpty ? UserEntity.fromRow(result.first) : null;
    } on PostgreSQLException catch (e) {
      throw Exception(e.message);
    } on Exception catch (e) {
      throw Exception(e);
    }
  }

  Future<UserEntity> update(
    String id, {
    String? setName,
    String? setEmail,
    String? setPassword,
    String? setImage,
    DateTime? setCreatedAt,
    bool? setEnabled,
  }) async {
    try {
      final valuesToUpdate = <String, dynamic>{
        if (setName != null) 'name': setName,
        if (setEmail != null) 'email': setEmail,
        if (setPassword != null) 'password': setPassword,
        if (setImage != null) 'image': setImage,
        if (setCreatedAt != null) 'createdAt': setCreatedAt,
        if (setEnabled != null) 'enabled': setEnabled,
      };

      if (valuesToUpdate.isEmpty) {
        throw Exception('You must provide at least one value to update!');
      }

      final result = await conn.query(
        'UPDATE tb_users SET ${valuesToUpdate.entries.map((e) => '${DSQLUtils.toSnakeCase(e.key)} = @${e.key}').join(', ')} WHERE id = @id RETURNING *;',
        substitutionValues: {
          'id': id,
          ...valuesToUpdate,
        },
      );

      return UserEntity.fromRow(result.first);
    } on PostgreSQLException catch (e) {
      throw Exception(e.message);
    } on Exception catch (e) {
      throw Exception(e);
    }
  }

  Future<UserEntity> delete(String id) async {
    try {
      final result = await conn.query(
        'DELETE FROM tb_users WHERE id = @id RETURNING *;',
        substitutionValues: {
          'id': id,
        },
      );

      return UserEntity.fromRow(result.first);
    } on PostgreSQLException catch (e) {
      throw Exception(e.message);
    } on Exception catch (e) {
      throw Exception(e);
    }
  }
}

class DSQL {
  late final PostgreSQLConnection _conn;

  late final UserRepository _userrepository;

  UserRepository get userrepository => _userrepository;

  DSQL({required String postgresURL}) {
    final uri = Uri.parse(postgresURL);
    final host = uri.host;
    final port = uri.port;
    final database = uri.pathSegments.isNotEmpty ? uri.pathSegments.first : '';
    final userInfo = uri.userInfo.split(':');
    final username =
        userInfo.isNotEmpty ? Uri.decodeComponent(userInfo[0]) : '';
    final password =
        userInfo.length > 1 ? Uri.decodeComponent(userInfo[1]) : '';

    _conn = PostgreSQLConnection(
      host,
      port,
      database,
      username: username,
      password: password,
    );

    _userrepository = UserRepository(_conn);
  }

  Future<void> init() async {
    await _conn.open();
    final root = Directory.current;
    final migrations = Directory(join(root.path, 'example', 'migrations'));
    final files = migrations
        .listSync()
        .where((file) => file.statSync().type == FileSystemEntityType.file);
    final versions = files
        .where((file) =>
            RegExp(r'^\V[\d]+\_\_(.*).sql$').hasMatch(basename(file.path)))
        .toList();
    for (final file in versions) {
      final version = await File(file.path).readAsString();
      await _conn.execute(version);
    }
  }
}
4
likes
0
points
12
downloads

Publisher

unverified uploader

Weekly Downloads

Dart SQL library for generating .dart files from .sql files

Homepage

License

unknown (license)

Dependencies

args, path, postgres, strings

More

Packages that depend on dsql