Skip to content

hw5#3

Open
pertsevpv wants to merge 4 commits intomasterfrom
lesson5
Open

hw5#3
pertsevpv wants to merge 4 commits intomasterfrom
lesson5

Conversation

@pertsevpv
Copy link
Copy Markdown
Owner

No description provided.

Comment thread src/main/kotlin/lesson5/DBInit.kt Outdated


private fun makeDropQuery(tableName: String) =
"DROP TABLE $tableName"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Существует конструкция DROP IF EXIST
то же самое касается конструкции CREATE TABLE а то можно поймать ошибки) когда кто-то что удалил или например уже создал

Comment thread src/main/kotlin/lesson5/Main.kt Outdated
}
line()

for (cust in CustomerData().getCustomers()) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

чет тут масло маслянное
custQueries.insert(CustomerData().getCustomers())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в других местах аналогично) кажется

Comment thread src/main/kotlin/lesson5/Main.kt Outdated

dbInit.createTable(producers)
dbInit.createTable(products)
line()
Copy link
Copy Markdown

@rumBo90 rumBo90 Mar 17, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

давай сделаем line с параметром
и туда будем передавать строку
fun line(title: String? = null) = println("\n-----${title ?: "///" }-----\n")

Comment thread src/main/kotlin/lesson5/Main.kt Outdated

fun oneToManyTest() {
val producers = Table("OTM_DB", "Producers", producerArgs, producerArgsMap)
val products = Table("OTM_DB", "Products", productArgs, productArgsMap)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я не совсем понял зачем тебе 2 базы) чисто для наглядности типо решил сделать?

val conn: Connection = DriverManager.getConnection("jdbc:sqlite:src/main/resources/$databaseName")
val stm: Statement = conn.createStatement()

override fun close() {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорош)

Comment thread src/main/kotlin/lesson5/DBService.kt Outdated

class DBService(private val databaseName: String) : AutoCloseable {

val conn: Connection = DriverManager.getConnection("jdbc:sqlite:src/main/resources/$databaseName")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а давай напишем тут вариацию под разные базы?
ну типо в конструктор еще будем передавать тип базы и возможные параметры к ее подключению?

Comment thread src/main/kotlin/lesson5/DBInit.kt Outdated
prepareAndExecute(dbService, sqlQuery)
println("Table $tableName dropped")
} catch (e: SQLiteException) {
println("Something went wrong while drop table")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

добавь в ошибку вывод инфы по названию таблицы) как бы в happy path у тебя есть а тут нет)

Comment thread src/main/kotlin/lesson5/DBQueries.kt Outdated
}
}

fun selectById(id: Int, table: Table = this.mainTable): String? {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну тут конечно ты там по логике намудрил)
некоторые вещи лучше упрощать) пусть даже они что-то дублируют)

Comment thread src/main/kotlin/lesson5/DBQueries.kt Outdated
preparedStatement.setInt(1, cost)
val rs = preparedStatement.executeQuery()
println("Selected elements with cost less $cost")
getStringsFromResponse(rs)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нигде не закрываешь ResultSet (rs)

Comment thread src/main/kotlin/lesson5/DBQueries.kt Outdated
return if (list.isEmpty())
null
else
list[0]
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

так низя) если у тебя тут лист а ты хотел 1 значение) низя брать первое
надо ошибку выбрасывать что мы ожидали 1 значение а тут лист.
тебе база не гарантирует что всегда будет отдавать одинаково ответ с какой то сортировкой

Comment thread src/main/kotlin/lesson5/DBQueries.kt Outdated

fun selectById(id: Int, table: Table = this.mainTable): String? {
DBService(databaseName).use { dbService ->
return try {
Copy link
Copy Markdown

@rumBo90 rumBo90 Mar 17, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в середине лямбды не стоит писать return, вот сюда лучше такие вещи помещать
DBService(databaseName).use { dbService ->

Comment thread src/main/kotlin/lesson5/DBQueries.kt Outdated
} catch (e: SQLiteException) {
println("Something went wrong while joining")
println(e.message)
emptyList()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

конструкции с вовзратом из catch выглядят честно говоря ужасно
но есть inline функции в котлине которые позволяют решить эту проблемку вот смотри)
p.s. код взял из другой функции но это не важно) смысл был показать

          runCatching {
               val sqlQuery = "SELECT * FROM $tableName WHERE ${args[3]} < ?"
               val preparedStatement = dbService.conn.prepareStatement(sqlQuery)
               preparedStatement.setInt(1, cost)
               val rs = preparedStatement.executeQuery()
               println("Selected elements with cost less $cost")
               getStringsFromResponse(rs)
           }.onFailure {
               println("Something went wrong while selecting from $tableName")
               println(it.message)
           }.getOrElse { emptyList() }


Comment thread src/main/kotlin/lesson5/DBQueries.kt Outdated
val sb = StringBuilder()
for (str in argsMap) {
when (str.value) {
"TEXT" -> sb.append(rs.getString(str.key))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

давай в ENUM данные значения

Comment thread src/main/kotlin/lesson5/DBQueries.kt Outdated
private fun getStringsFromResponse(rs: ResultSet, argsMap: Map<String, String> = this.argsMap): List<String> {
val ans = mutableListOf<String>()
while (rs.next()) {
val sb = StringBuilder()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ты в цикле каждый раз пересоздаешь StringBuilder

давай вынесем его наверх и просто будем в конце цикла очищать

toString тут тебе точно возращает новую строку так что будет все ок

Copy link
Copy Markdown

@rumBo90 rumBo90 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если честно) очень намудрил))) Но это тоже полезно, потому что это нормальное желание человека сделать хорошо) но тут самое сложное научится видеть эту грань, где надо остановится. Так что в целом все равно молодец но пройтись по комментариям поправь

и давай еще по пакетам разнесем ) чтоб как то структурировать код

) {

fun createAllTables(){
for (t in tables)createTable(t)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tables.foreach{createTable(it)}

getStringsFromResponse(rs, table.argsMap)
} catch (e: SQLiteException) {
val ans = getStringsFromResponse(rs, table.argsMap)
rs.close()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

от тоже реализует AutoCloseable

for (el in args.indices) {
append(args[el])
if (el != args.size - 1)
append(", ")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

или в 1 строчку или операторные скобки

Copy link
Copy Markdown

@rumBo90 rumBo90 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в целом норм но подправь еще немного

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants